android - 使用 cursorAdapter 滚动时复选框丢失状态
问题描述
我目前正在开发一个简单的 Android 应用程序,它允许用户使用复选框从 sqlite 数据库中添加/删除/删除记录。主要活动有一个列表视图,它从练习适配器呈现对象。该适配器从光标适配器扩展而来。我遇到的问题是选择一个复选框,然后向下滚动列表以使该复选框不在视图中,状态丢失。以下是我的主要活动和锻炼适配器的摘录:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbManager = new DBManager(this);
dbManager.open();
adapter = new ExerciseAdapter(this, dbManager.fetch());
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
}
public void deleteExercise(View view) {
for (int i = 0; i < adapter.getCount(); i++) {
CheckBox c = listView.getChildAt(i).findViewById(R.id.checkBox);
if (c.isChecked()) {
deleteIds.add(adapter.getItemId(i));
}
}
for (Long deleteId : deleteIds) {
dbManager.delete(deleteId);
adapter.update(dbManager.fetch());
}
}
运动适配器:
public class ExerciseAdapter extends CursorAdapter {
public ExerciseAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.exercise, parent, false);}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// Find fields to populate in inflated template
TextView exerciseTitle = view.findViewById(R.id.exerciseTitle);
TextView exerciseDesc = view.findViewById(R.id.exerciseDescription);
TextView exerciseDate = view.findViewById(R.id.exerciseDate);
// Extract properties from cursor
String title = cursor.getString(cursor.getColumnIndexOrThrow("title"));
String desc = cursor.getString(cursor.getColumnIndexOrThrow("description"));
String date = cursor.getString(cursor.getColumnIndexOrThrow("date"));
// Populate fields with extracted properties
exerciseTitle.setText(title);
exerciseDesc.setText(String.valueOf(desc));
exerciseDate.setText(String.valueOf(date));
}
public void update(Cursor cursor) {
this.swapCursor(cursor);
this.notifyDataSetChanged();
}
}
这是采用的代码,因此希望保持类与现在的相似,除非没有其他选择并且需要进行大的更改。
谢谢。
解决方案
推荐阅读
- c# - 为 identityserver4 身份验证处理本地数据
- reactjs - Storybook (v6) 中是否有内置组件,可以帮助您记录模型?
- javascript - 如何在 React App 中使用 Axios 从 S3 预签名 URL 下载 BLOB 文件?
- r - 使用从管道创建的 ggplot 突出显示单个数据点
- swift - 在 AVQueuePlayer 中播放完最后一项后如何显示工作表视图?
- excel - Google 地球 KMZ 重组
- c# - 克服 32 位限制,使用由数百万单位转换的 System.Drawing.Graphics 表面
- emeditor - Emeditor 在某个正则表达式后崩溃
- amazon-web-services - AWS - 如何根据 Cloudtrail 事件名称触发 Lambda
- c - typedef - 没有花括号的 Typedef