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"/>
.....
</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. |
....
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] ,
[5 =>true] shift to be [4 => true],
[6 =>true] changes to be[5 => true]......
delCounter = 1
}
when for( i = 2 )
{
[1 =>true] ,
[5 =>true] changes to be[4 => true]......
delCounter = 2
}
留言
張貼留言