我有一个非常相似的问题这个帖子 https://stackoverflow.com/questions/5444355/android-listview-with-checkbox-problem。在 ListView 的每一行中,我都有一个带有侦听器的复选框。监听器更新数据库行。
@Override
public void bindView(View v, Context context, Cursor c) {
TextView tvA = (TextView) v.findViewById(R.id.adi_tv_activity);
CheckBox cb = (CheckBox) v.findViewById(R.id.adi_cbox);
tvA.setText(c.getString(c.getColumnIndex("name")));
final long id = c.getLong(c.getColumnIndex("_id"));
final Context ctx = context;
cb.setOnCheckedChangeListener(new OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
ObjDBF dbf = new ObjDBF(ctx); //Object thet update db
if(isChecked) {
dbf.tbActivitiesUpdateState(id, true);
} else {
dbf.tbActivitiesUpdateState(id, false);
}
}
});
if (c.getBoolean(c.getColumnIndex("state"))) {
cb.setChecked(true);
} else {
cb.setChecked(false);
}
}
我有两个问题。
- 滚动问题。移动列表时,我丢失了从屏幕上消失的行的复选框状态。
- 每当我使用 setChecked 时,都会调用侦听器,从而导致新的数据库更新。
为了解决滚动问题,我想在每次更新数据库时使用adapter.changeCursor,但对于第二个问题,它会导致循环。
我还尝试使用数组,如上面链接帖子的第二个答案中所示,但它使用方法 getView od 适配器,我有一个cursorAdapter 并在 newView 和 bindView 中工作
我该如何解决这个问题?
编辑:auselen 解决方案有效,但它创建和销毁了很多侦听器,还有其他更有效的解决方案吗?
为了避免在侦听器上触发回调,您应该通过以下方式取消注册现有侦听器:cb.setOnCheckedChangeListener(null)
然后设置cb.setChecked(c.getBoolean(c.getColumnIndex("state")))
then cb.setOnCheckedChangeListener()
again.
但是你应该想出更好的使用方法OnCheckedChangeListener
,因为您最终会创建超出需要的侦听器。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)