Jon Wells
Jon Wells

Reputation: 4259

ListView toggle choice mode

I have a ListView (technically its a ListFragment, but I dont think that changes the question) which displays its results uisng a SimpleCursorAdapter.

    adapter = new SimpleCursorAdapter(
            getActivity(),
            R.layout.item,
            null,
            new String[] {"Name"},
            new int[] {R.id.Name}
            );

    setListAdapter(adapter);

(The Cursor is set/swapped in onStart).

I want to give the user the ability to toggle choice mode (which will than be used to display only the checked items). A bit like an SMS application when you put messages in "batch mode" which allows you to select multiple conversations which can the be deleted, saved etc. Do I set a new adapter or just change the existing ones properties? the ListView will need re-drawing anyway to reflect changes.

Upvotes: 0

Views: 6075

Answers (3)

Daniel De León
Daniel De León

Reputation: 13679

Like Vikram Bodicherla answer.

  1. setChoiceMode to enable MULTI_SELECT on the ListView.
  2. Set in your custom item layout a background that show the selected state like:

    android:background="?android:attr/activatedBackgroundIndicator"
    

Upvotes: 1

Jon Wells
Jon Wells

Reputation: 4259

This is a suprisingly simple answer. The problem was I was calling the method in onCreate before onCreateView had inflated the List. Stupdily this was just to test the function. Once I moved it to onStart and later into its intended location in the FragmentActivity the following worked fine:

public void toggleAdapter()
{           
    ListView listView = getListView();

    if (listView.getChoiceMode() == ListView.CHOICE_MODE_MULTIPLE)
    {
        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

        adapter = new SimpleCursorAdapter(
                getActivity(),
                R.layout.item,
                dashboardCursor,
                new String[] {"Name"},
                new int[] {R.id.Name}
                );
    }
    else
    {
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

        adapter = new SimpleCursorAdapter(
                getActivity(),
                R.layout.dashboard_list_item_multiple_choice,
                dashboardCursor,
                new String[] {"Name"},
                new int[] {R.id.Name}
                );
    }


    listView.setAdapter(adapter);
}

Upvotes: 0

Vikram Bodicherla
Vikram Bodicherla

Reputation: 7123

You have to do two things.

  1. Use the ListView's setChoiceMode method to enable MULTI_SELECT on the ListView.

  2. Create a 'Selector' to define a 'selected' or 'checked' state and set this as a style element on your R.layout.item.

Upvotes: 1

Related Questions