Android 复选框删除

标签 android listview checkbox

我遇到了一些严重的问题,我有一个 ListView ,其中填充了数据库中的条目, ListView 中的每一行都有一个自定义行 (TextView1|TextView2|TextView3|Checkbox)。

我想做的就是在每个复选框上放置一个监听器,以便在选中时将其从 ListView 中删除并从数据库中删除。我有一个函数,当它被传递给 Textview1 的值时,它会从数据库中删除该行。

我遇到的问题是试图从选中的框或 TextView 值中获取行 ID。我到处搜索,但仍然无法正常工作

复选框

Cursor cursor = db.getAllItems();

    //String[] columns = new String[] {db.KEY_NAME, db.KEY_CODE, db.KEY_ROWID};
    final String[] columns = new String[] {db.KEY_ITEM_NAME, db.KEY_MEASUREMENT, db.KEY_UNIT};

    int[] to = new int[] {R.id.ingredientName, R.id.ingredientMeasurement, R.id.ingredientUnit};

    final SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(this,R.layout.row4, cursor, columns, to, 0);

    final ListView shoppingList = (ListView) findViewById(R.id.shoppingList);
    shoppingList.setClickable(false);
    //shoppingList.setChoiceMode(shoppingList.CHOICE_MODE_SINGLE);
    shoppingList.setAdapter(myCursorAdapter);

    CheckBox check = (CheckBox) findViewById(R.id.checkBox1);
    check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (buttonView.isChecked()) {
                //how do i get the row_id or the text view value?
            } else {
                //do nothing
            }
            }

        });

最佳答案

据我所知,这个实现是不可能的。您必须创建自定义适配器

public class CustomAdapter extends SimpleCursorAdapter{

    public CustomAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
        super(context, layout, c, from, to);
    }

    public View getView(final int position, View convertView, ViewGroup parent){
        View view = super.getView(position, convertView, parent);
        CheckBox check = (CheckBox) findViewById(R.id.checkBox1);
        check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (buttonView.isChecked()) {
                // position will give you the position of the clicked element from where you can fetch your data
            } else {
                //do nothing
            }
            }

        });
        return view;
    }
}

你可以使用它

CustomAdapter adapter = new CustomAdapter(this, R.layout.row_layout, cursor, from, to);
list.setAdapter(adapter);

关于Android 复选框删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35227689/

相关文章:

java - 将字符串分成几行

android - 声音在 MacOS 上的 Android 模拟器中不起作用

android - 无法将图像定位到 android 的自定义 ListView 中的所需位置

listview 中的 asp.net 复选框调用 javascript 代码 onchange

android - 如何将复选框绑定(bind)到图像

html - 将自定义图像设置为没有强制标签的复选框

android - System.loadLibrary(...) 在我的情况下找不到 native 库

android - AsyncTask 不会进入 onPostExecute()

java - 将带有自定义对象的列表传递给另一个 android Activity

java - 单击按钮更新 ListView 行项目