Fix Android ListViewItem not highlighted when selecting programmatically


I have a ListView
like this:
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:choiceMode="singleChoice"
android:listSelector="?attr/colorPrimarySurface" />
However, when I tried to highlight on the first item by default using the performItemClick
method, it won't work.
listView.post {
listView.performItemClick(
listView.getChildAt(0),
0,
listView.adapter.getItemId(0)
)
}
After searching on the internet, i found the solution, two lines needed to be added before calling the performItemClick
method.
listView.requestFocusFromTouch();
listView.setSelection(0);
Now it works as expected.
ref: https://stackoverflow.com/a/34566428