我需要在异步任务中更改开关的状态。我在自定义适配器的交换机上设置了onClickListner(),并将其引用传递给异步任务。在我的异步任务中,我尝试使用发布进度和onProgressUpdate来更新交换机的状态。但交换机的状态在UI中没有改变。有人可以帮助我吗?无法从异步任务更改开关状态
下面是我的代码:
DeviceAdapter.java
public class DeviceAdapter extends ArrayAdapter<Device> {
private List<Device> deviceInfo;
private Device device;
private View customView;
private Switch socketSwitch;
private DevicesInfoDbAdapter devicesInfoDbAdapter;
public DeviceAdapter(Context context, List<Device> deviceInfo) {
super(context, R.layout.row_device_details, deviceInfo);
this.deviceInfo = deviceInfo;
device = deviceInfo.get(0);
devicesInfoDbAdapter = DBFactory.getDevicesInfoDbAdapter(getContext());
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
customView = layoutInflater.inflate(R.layout.row_device_details, parent, false);
socketSwitch = (Switch) customView.findViewById(R.id.socketSwitch);
ImageButton btnRefresh = (ImageButton) customView.findViewById(R.id.btnRefresh);
btnRefresh.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("socketswitch1",""+socketSwitch);
DeviceStatusRefreshAsync deviceStatusRefreshAsync = new DeviceStatusRefreshAsync(socketSwitch);
deviceStatusRefreshAsync.execute();
}
});
return customView;
}
}
DeviceStatusRefreshAsync.java
public class DeviceStatusRefreshAsync extends AsyncTask {
private Switch socketSwitch;
public DeviceStatusRefreshAsync(Switch socketSwitch) {
this.socketSwitch = socketSwitch;
}
@Override
protected Object doInBackground(Object[] params) {
publishProgress(); //Calling to update the switch state
return null;
}
@Override
public void onProgressUpdate(Object[] values) {
socketSwitch.setChecked(true); //Switch state not changing in the UI
}
}
也许你应该调用invalidate? – Karoly
只需点击btnRefresh即可更新deviceInfo列表。 – Pavya
socketSwitch始终是最后一次getView调用中的一个......你需要修正它:最后在右侧范围或get/setTag ......当然,除非你不保存状态 – Selvin