I would like to select an item from a ListView by default (when the view is created). And I want to do it grammatically. I tried the answer from this Question, but it does not work for me.
I have the followings...
MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
arrayList = new ArrayList<String>();
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");
arrayList.add("5");
arrayList.add("6");
arrayList.add("7");
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
//listView.setSelection(3);
listView.setItemChecked(3, true);
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:listSelector="@drawable/list_item_selector"
android:drawSelectorOnTop="true" />
</LinearLayout>
list_item_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_activated="true"
android:state_pressed="true"
android:state_selected="true"
android:drawable="@color/red" />
<item
android:state_activated="false"
android:state_pressed="false"
android:state_selected="false"
android:drawable="@color/black" />
</selector>
I tried many combinations of the following methods in .java
listView.setSelection(i);
listView.setItemChecked(i, true);
lv_stakeoutPoints.performClick();
listViewAdapter.notifyDataSetChanged();
But none of the combinations works properly. Does anyone solve this issue?
(By the way, why is it so difficult to do this?)
FYI, I am developing with Android 4.1.2