Search code examples
androidlistviewsimplecursoradapter

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.


Solution

  • 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);
    }