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
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With