Reputation: 2478
I hava a problem with my code. I want to select the first element in a ListFragment by default (when the Activity is visible by the first time, I want the first element to be selected) but I am not able to do that. This is my code:
In ListFragment (onActivityCreated):
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
R.layout.fragment_selector, ActivityMain2.mTitleArray);
setListAdapter(adapter);
ListView listView = getListView();
listView.setSelector(R.drawable.fragment_listselector);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listView.setItemChecked(1, true);
listView.setSelection(1);
listView.setSelected(true);
adapter.notifyDataSetChanged();
layout/fragment_selector:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
android:textSize="32sp" >
</TextView>
drawable/fragment_listselector:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/default_color" android:state_selected="false"/>
<item android:drawable="@color/pressed_color" android:state_selected="true"/>
</selector>
Any help? Thank you
Upvotes: 0
Views: 544
Reputation: 4255
So your Question is a duplicate of this Question
ListView doesn't keep items selected, so the custom selector does not work! You have to write your own Adapter and remember the selected Item with a field, as the answer states.
Then just call listView.setSelection(0)
in onCreate
and you are fine.
I have used the code from there myself and it works fine.
Upvotes: 1