首页 > 解决方案 > 使用 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();
    }
}

这是采用的代码,因此希望保持类与现在的相似,除非没有其他选择并且需要进行大的更改。

谢谢。

标签: androidcheckboxadapter

解决方案


推荐阅读