Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android:以 ListView + SimpleCursorAdapter + CheckBox 實現批量刪除

編輯:關於 Android 程式設計

最近專案有個需求:對筆記列表進行批量刪除。功能本身實現起來並不難,網上也有許多可参考的範例。但這個專案有個特別之處——它使用的是 SimpleCursorAdapter 來綁定 ListView,而網上大多數範例都是基於 ArrayAdapter、SimpleAdapter 或 BaseAdapter。因此這裡特別記錄一下解決方法。

常見的批量刪除實現方式

網路上大致有以下幾種做法:

  1. ArrayAdapter + ListView + CheckBox
  2. BaseAdapter + ListView + CheckBox
  3. 使用 ViewBinder 添加 CheckBox

解決方法

針對 SimpleCursorAdapter,可以採用以下三步驟:

  1. 繼承 SimpleCursorAdapter,重寫 getView 方法。
  2. 在自訂的適配器中新增一個集合,保存被選中的 ListView 項目 id。
  3. 對外提供一個取得被選中項目 id 集合的方法。
public class CheckBoxAdapter4TextNote extends SimpleCursorAdapter {
    private ArrayList<Integer> selection = new ArrayList<Integer>();  // 記錄被選中項目 id
    private int mCheckBoxId = 0;  // 樣式對應的 xml 資源中的 checkbox id
    private String mIdColumn;     // 資料庫表的 id 名稱

    public CheckBoxAdapter4TextNote(Context context, int layout, Cursor c,
            String[] from, int[] to, int checkBoxId, String idColumn, int flags) {
        super(context, layout, c, from, to, flags);
        mCheckBoxId = checkBoxId;
        mIdColumn = idColumn;
    }

    @Override
    public int getCount() {
        return super.getCount();
    }

    @Override
    public Object getItem(int position) {
        return super.getItem(position);
    }

    @Override
    public long getItemId(int position) {
        return super.getItemId(position);
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);
        final CheckBox checkbox = (CheckBox) view.findViewById(mCheckBoxId);
        checkbox.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Cursor cursor = getCursor();
                cursor.moveToPosition(position);
                checkbox.setChecked(checkbox.isChecked());
                if (checkbox.isChecked()) {
                    // 若被選中則將 id 保存到集合中
                    selection.add(cursor.getInt(cursor.getColumnIndex(mIdColumn)));
                } else {
                    // 否則移除
                    selection.remove(new Integer(cursor.getInt(cursor.getColumnIndex(mIdColumn))));
                    Toast.makeText(context,
                        "has removed " + cursor.getInt(cursor.getColumnIndex(mIdColumn)), 0).show();
                }
            }
        });
        return view;
    }

    /** 回傳被選中項目的集合 */
    public ArrayList<Integer> getSelectedItems() {
        return selection;
    }
}

呼叫方式

List<Integer> bn = XXX.getSelectedItems();
for (int id : bn) {
    // TODO 執行刪除操作
}

重點:相較於直接操作 Adapter 資料,這種做法巧妙地利用了 SimpleCursorAdapter 內建的 Cursor,透過 getCursor().moveToPosition(position) 定位到被點擊的項目,再從指定的 id 欄位取出對應的資料庫主鍵,收集進 selection 集合中。最後只需遍歷這個集合執行刪除,即可完成批量操作。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved