我有一个类Devices
,它使用setChecked(boolean)
存储Switch的已检查状态,并通过isChecked()
方法获取。
使用它,切换后我会保持切换状态一次。
但是,如果我将开关的状态更改为ON,则每次向下滚动并返回到开关时,都会调用setOnCheckedChangeListener
。我该如何防止这种情况?
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
DeviceHolder holder = null;
Devices devices = list.get(position);
String id = devices.id;
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new DeviceHolder();
holder.devTxt = (TextView) row.findViewById(R.id.devdesc);
holder.nameTxt = (TextView) row.findViewById(R.id.devname);
holder.toggleSwitch = (Switch) row.findViewById(R.id.toggleswitch);
holder.txt = (TextView) row.findViewById(R.id.debug);
final int i=id;
final Switch tswitch = holder.toggleSwitch;
holder.toggleSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
//Comes here every time I scroll to a button that is ON
Control._service.write(i);
list.get(position).setChecked(tswitch.isChecked());
}
});
holder.devTxt.setText(devices.dev);
holder.nameTxt.setText(devices.name);
holder.txt.setText(id);
if (tswitch.isChecked() != devices.isChecked())
holder.toggleSwitch.setChecked(devices.isChecked());
return row;
}