The Best For Deleting Multiple Selected Items In ListView | Android

金閣寺


if developer want to have the selected effect(as bright color on when the item is selected), I refer to use both of 
setActivated(true) and setClickable(true) as below:
.....
mScanList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mScanList.setAdapter(ListAdapter);
mScanList.setClickable(true);
mScanList.setActivated(true);

Finally, the xml file should look like below :
<selector xmlns:android="http://schemas.android.com/apk/res/android"
    android:enterFadeDuration="@android:integer/config_shortAnimTime"
    android:exitFadeDuration="@android:integer/config_shortAnimTime" >
       
     .....

     <item android:drawable="...." android:state_activated="true"/>
     <item android:drawable="...." android:state_selected="true"/> 

     .....
</selector>

p.s. why state_activated and state_selected appear here at the same time? Because status_selected is for older API levels, and state_activated works for almost all API levels. So, even it works without state_selected is fine.



Let's watch the diagram below. When you want to delete items in ListView with multiple selecting, watch out the reaction of memory address number.
Adapter of ListView memory address processing after an item removed.
Every time you delete an item in ListView via for-loop(or other loops), don't forget to tell the next one : the memory address is changed. Consequently, the better way is as below :
....
MyListAdapter adptr = (MyListAdapter)mList.getAdapter();
SparseBooleanArray checkeds = mList.getCheckedItemPositions();

// use it to remind the next one don't forget subtract 1 in list.
int delCounter = 0;  

for(int i = 0; i < checkeds.size(); i++)
{
        int key = checkeds.keyAt(i);
        if(checkeds.get(key))
{
adptr.remove(adptr.getItem(key - delCounter));
delCounter += 1;
        }
}
adptr.notifyDataSetChanged();
mList.clearChoices();
mList.requestLayout();

The getCheckedItemPositions() method will return a SORT result as a map, and we can get keys in the memory via keyAt(index number). e.g. { [index 0]: 1=>true, [index 1]: 3=>true, [index 2]: 5=>true, [index 3]: 6=>true }. Finally, it works with remove() method in ArrayAdapter class, and every time remove the item in adapter, the others will shift forward after remove() called. e.g. 

when for( i = 1)
{
[1 =>true] ,
[3=>true](deleted), 
[5 =>true] shift to be [4 => true], 
[6 =>true] changes to be[5 => true]......

delCounter = 1
}

when for( i = 2 )
{
[1 =>true] ,
[3=>true](deleted), 
[4 =>true](deleted), 
[5 =>true] changes to be[4 => true]......

delCounter = 2
}







留言

這個網誌中的熱門文章

7-ELEVEN 電子發票明細查詢方式

Java 使用 regular expression 正則表達,過濾特殊字元,反斜線處理重點

Ubuntu GUI中,無法啟動WIFI連結解決方法