Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ListFragment set initial selection

hopefully a quick question. How would I go about setting the default selection on a ListFragment. I want the activity to launch with the top list item already selected. Thanks

like image 578
Nick Avatar asked Feb 21 '26 08:02

Nick


1 Answers

Taken from the official example in the Android docs (http://developer.android.com/guide/components/fragments.html#Example) and in the support library API demos:

The ListFragment in that example uses getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); and getListView().setItemChecked(index, true); in the ListFragment's onActivityCreated method to make a list item selected/highlighted, where index is taken from a local variable set to 0 by default. So you'd have something like:

public static class TitlesFragment extends ListFragment {
    boolean mDualPane;
    int mCurCheckPosition = 0;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // Populate list with our static array of titles.
        // (Replace this with your own list adapter stuff
        setListAdapter(new ArrayAdapter<String>(getActivity(),
            android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES));

        if (savedInstanceState != null) {
            // Restore last state for checked position.
            mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
        }

        getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        getListView().setItemChecked(mCurCheckPosition, true);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("curChoice", mCurCheckPosition);
    }

    // ... the rest of the ListFragment code ....
}

Take a look at that example I linked to at the top and that should get you up and running!

like image 176
LearningNerd Avatar answered Feb 23 '26 03:02

LearningNerd