我在CustomAdapter中实现了多个开关。
下面的CustomAdapter代码。
sche_swt = (Switch)convertView.findViewById(R.id.ctschedule);
loc_swt = (Switch)convertView.findViewById(R.id.ctlocation);
sche_swt.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean is_checked) {
if (compoundButton.getId() == R.id.ctschedule) {
if (is_checked == true) {
contactItemList.get(position).setSchedule(true);
} else {
contactItemList.get(position).setSchedule(false);
}
}
}
});
if (contactItemList.get(position).getScheduleInt() == 1) {
sche_swt.setChecked(true);
}
else
sche_swt.setChecked(false);
loc_swt.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean is_checked) {
if (compoundButton.getId() == R.id.ctlocation) {
if (is_checked == true) {
contactItemList.get(position).setLocation(true);
}
else {
contactItemList.get(position).setLocation(false);
}
}
}
});
if (contactItemList.get(position).getLocationInt() == 1) {
loc_swt.setChecked(true);
}
else
loc_swt.setChecked(false);
return convertView;
}
一行似乎是
name
phone_number
switch 1 | switch 2
我存储了开关状态
例如:
1 line = switch(false) | switch(true)
2 line = switch(false) | switch(true)
3 line = switch(true) | switch(false)
......等等。
完成我的应用后,重新执行listview结果如
1 line = switch(true) | switch(false)
2 line = switch(true) | switch(false)
3 line = switch(true) | switch(false)
出了什么问题?
答案 0 :(得分:0)
问题可能出在侦听器中使用位置变量或调用setChecked方法。尝试下面,我只做了调度切换,为位置切换做同样的事情。
sche_swt = (Switch)convertView.findViewById(R.id.ctschedule);
loc_swt = (Switch)convertView.findViewById(R.id.ctlocation);
// setting tag
sche_swt.setTag(position)
loc_swt.setTag(position)
// you need to remove the listener because when you call setChecked()
// it will invoke the listener unnecessarily and it might affect the
// state of the view.
sche_swt.setOnCheckedChangeListener(null);
if (contactItemList.get(position).getScheduleInt() == 1) {
sche_swt.setChecked(true);
}
else
sche_swt.setChecked(false);
sche_swt.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean is_checked) {
if (compoundButton.getId() == R.id.ctschedule) {
// using the tag to get the position.
int position = compoundButton.getTag();
if (is_checked == true) {
contactItemList.get(position).setSchedule(true);
} else {
contactItemList.get(position).setSchedule(false);
}
}
}
});
return convertView;
如果您不知道标签是什么或我使用它的原因而不是位置,请阅读https://stackoverflow.com/a/5291891/1749223。我希望以上解决问题。