1. 程式人生 > >Android學習--實現listview批量刪除的功能

Android學習--實現listview批量刪除的功能

繼放下了上次的專案兩個月之後,領導又有了新的需求,她發現要刪除已經到期的倒數日太多,又不能批量刪除。所以我就想做一個跟微信一樣的,長按彈出選單,直接刪除當前的,或者是多選刪除。
這就需要用到checkbox。
首先是修改xml檔案。直接在list-item的文字前面加checkbox即可

<Checkbox
    android:id="delete_cb"
    android:width="wrap_content"
    android:height="wrap_content"
    android:visibility="gone"
    />

然後修改count in的xml,增加一個刪除按鈕。

<Button
    android:id="delete_btn"
    android:width="match_parent"
    android:height="wrap_content"
    android:visibility="gone"
    />

之後就是程式碼工作了。其實實現不難,要點是給Adapter類增加兩個HashMap來記錄(其實Arraylist也可以。不過hashmap能有一個對應關係更加自由)

//記錄某一項的checkbox是否可見
private HashMap<
Integer,Integer> checkBoxVisibility; //記錄某一項的checkbox是否被選擇 private HashMap<Integer,Boolean> checkBoxSelected;

記得初始化

checkBoxVisibility=new HashMap<Integer,Integer>();
checkBoxSelected=new HashMap<Integer,Boolean>();
for(int i=0;i<dates.size();i++){
        checkBoxVisibility.
put(i,View.GONE); checkBoxSelected.put(i, false); }

因為每一項都有一個checkbox,所以我們在viewholder中加入

class ViewHolder {
            private LinearLayout countToLayout;
            private TextView change;
            private TextView content;
            private TextView date;
            private CheckBox check;
}

之後getView函式中需要新增程式碼。如果是新建的項(if (convertView == null)),則要在hashmap中新增,如果是已經有的項(else),則一般都是經過刪除或者是新建後順序變了需要重新調整。
接下來是個卡住的地方,怎麼監聽checkbox已經被勾選了呢?我們需要在Adapter中加listener。

final int position1=position;//position是當前項的位置
vh.check.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
        checkBoxSelected.put(position1, true);
    }
});

接下來是刪除的邏輯:
要點:因為我是用的for來迴圈,檢視哪項是被勾選的,如果是被勾選,則刪除在資料庫中的資料跟list中的,這裡要注意陣列不能越界,所以list的下標是順序減去被刪除的數量。

case R.id.delete_btn:
int count=0;
for(int order=0;order<adapter.visibilityMap().size();order++){          if(adapter.selectedMap().get(order)==true){
        Day d=dayLists.get(order-count);
        String content=d.content;
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.delete("CountDays1", "content1=?", new String[] { content });                
        dayLists.remove(order-count);
        count++;
            }
            }
            for(int order=0;order<adapter.getCount();order++){
                adapter.checkBoxSelected.put(order, false);
                adapter.checkBoxVisibility.put(order,View.GONE);
            }
            adapter.notifyDataSetChanged();
            add.setText("新建");
            delete.setVisibility(View.GONE);
            checking=false;
            Toast.makeText(this, "已刪除", Toast.LENGTH_SHORT).show();
            break;

還有一些跳轉的邏輯就不說了