Lukas Gabsi Lukas Gabsi - 4 years ago 162
Android Question

Remove all selected items from a checkable ListView in Android

I'm having trouble removing just the items that are checked.
I have already tried to set them invisible but it didn't to the job. It just made some random items invisible.

Here's my code to populate the ListView:

public void populate(){
String [] result = getIntent().getStringExtra(EXTRA_RESULT).split(";");
orderArray = new ArrayList<>(Arrays.asList(result));
chl = (ListView) findViewById(R.id.checkableList);

chl.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
adapter = new ArrayAdapter<>(this, R.layout.rowlayout, R.id.txt_lan, orderArray);
chl.setAdapter(adapter);
chl.setOnItemClickListener(new AdapterView.OnItemClickListener(){

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

CheckedTextView ctv = (CheckedTextView) view;

if(ctv.isChecked()){
selectedItemsPos.add(position);
}
selectedItemsPos.remove(position);
}
}
});
}


and here is how I've tried to remove the items:

public void removeSelectedItems(MenuItem menuItem){
for(int i=0; i<selectedItemsPos.size();
orderArray.remove(selectedItemsPos.get(i));
}
adapter.notifyDataSetChanged();
}

Answer Source

Use a SparseBooleanArray to get the checked items and then delete the same and refresh listview.

   public class MainActivity extends Activity 
    {
        ListView lv;
        ArrayAdapter<String> adapter;
        Button delete;
        ArrayList<String> data = new ArrayList<String>();
        SparseBooleanArray mCheckStates ;
        @Override
        protected void onCreate(Bundle savedInstanceState) 
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.test);
            lv = (ListView)findViewById(R.id.listView1);
            lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
            delete = (Button)findViewById(R.id.button1);
            data.add("Windows");
            data.add("Android");
            data.add("Apple");
            data.add("Blackberry");
            adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_multiple_choice, data);
            lv.setAdapter(adapter);

            delete.setOnClickListener(new OnClickListener()
            {
            @Override
            public void onClick(View v)
            {

                 SparseBooleanArray checkedItemPositions = lv.getCheckedItemPositions();
                 int itemCount = lv.getCount();

                 for(int i=itemCount-1; i >= 0; i--){
                     if(checkedItemPositions.get(i)){
                         adapter.remove(data.get(i));
                     }
                 }
                 checkedItemPositions.clear();
                 adapter.notifyDataSetChanged();

            }
            });
        }
    }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download