无法从异步任务更改交换机状态

时间:2015-06-22 10:27:08

标签: android android-asynctask android-switch

我需要从异步任务内部更改交换机的状态。我在自定义适配器的交换机上设置了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
    }
}

1 个答案:

答案 0 :(得分:1)

不使用OnClickListener而是使用 OnCheckedChangeListener 而不是使用onProgressUpdate,而是使用 onPostExecute 来更改切换状态。