ageektrapped
ageektrapped

Reputation: 14562

Implement Select All with multiple select ListView in Android

I'm trying to implement a Select All menu item for a ListView in a ListViewActivity. The relevant parts of my ListViewActivity:

public class MyListViewActivity extends ListActivity
{


   @Override
   protected void onCreate(Bundle savedInstanceState)
   {
      super.onCreate(savedInstanceState);

      ArrayList<String> data = createDataList();      
      setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, data));
      getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
      getListView().setItemsCanFocus(false);
   }


   @Override
   public boolean onMenuItemSelected(int featureId, MenuItem item)
   {
      if (item.getItemId() == R.id.delete)
      {
         //TODO: delete the checked items
         return true;
      }
      if (item.getItemId() == R.id.select_all)
      {
         for (int i = 0; i < getListView().getCount(); i++)
            getListView().setSelection(i);
         return true;
      }
      return super.onMenuItemSelected(featureId, item);
   }

I've browsed around stackoverflow.com and the google; the above is something that should work. But it doesn't. setSelection(i) appears to be the method I want to call on ListView but it's not working as advertised.

What am I doing wrong? Is this even possible on Android in code?

Upvotes: 0

Views: 4818

Answers (2)

Cheryl Simon
Cheryl Simon

Reputation: 46844

I think the function you are looking for is setItemChecked.

Upvotes: 3

dharmendra
dharmendra

Reputation: 7881

try this one .

ListView listview = getListView();
if (item.getItemId() == R.id.select_all)
      {
         for (int i = 0; i < listview.getCount(); i++)
            listview.setItemChecked(i, true);
      }

Upvotes: 4

Related Questions