android – getCheckedItemCount()在游标更改后返回错误的值

我想要做的是将ListView放在我的应用程序中,该应用程序使用内部SQLite数据库来获取数据.当用户点击新数据时,通过执行新查询从DB获取.

我已经实现了ListView项的自定义视图,它扩展了LinearLayout并实现了Checkable接口.作品.

获得了基于CursorAdapter的自定义适配器.在OnCreate()中,我使用空光标为ListView设置适配器.

ListView markersList = (ListView) findViewById(R.id.markersList);

Cursor c = null;
MarkersListAdapter adapter = new MarkersListAdapter(this, c, 0);
markersList.setAdapter(adapter);

接下来在AsyncTask中我在doInBackground()中查询数据库,该数据库将新游标传递给onPostExecute()以更新ListView.我这样做:

adapter.changeCursor(newCursor);

然后我默认检查所有项目(用户只需取消选中不需要的项目)

for(int i = 0; i < this.markersList.getCount(); i++)
{        
    this.markersList.setItemChecked(i, true);
}

到现在为止还挺好.但是,当我这样做

int s = this.markersList.getCheckedItemCount();

我错了价值.我猜它与旧光标相关联.只有当新游标中的行数小于新游标中的行数时,才会发生这种情况.

一般来说,我得到这样的东西

int s = this.markersList.getCheckedItemCount();   // s = 7
int d = this.markersList.getCount();              // d = 5

这个问题有方法解决吗?

最佳答案 最简单的解决方案是手动清除检查计数:

this.markersList.clearChoices();
for(int i = 0; i < this.markersList.getCount(); i++)
{        
    this.markersList.setItemChecked(i, true);
}
点赞