1

I have a ListView whose items become highlighted when they are selected by the user. However, at the start of the Fragment, this ListView lives in, none of the items are highlighted because the user hasn't selected any yet.

I'm trying to programmatically select the first item in my ListView (the default item) because the user hasn't selected one yet.

The solution (that sort of works) I stumbled across throughout StackOverflow was,

listView.clearFocus();
listView.requestFocusFromTouch();
listView.setSelection(defaultPosition);

My ListView's xml looks like:

<ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:divider="@null"
    android:dividerHeight="0dp"
    android:choiceMode="singleChoice"/>

and the background drawable the ListView items listen to for state changes is:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/blue_linear_layout" android:color="@color/white" android:state_selected="true"/>
    <item android:drawable="@drawable/blue_linear_layout" android:color="@color/white" android:state_activated="true"/>
    <item android:drawable="@drawable/gray_linear_layout" />
</selector>

The Problem

The above code does highlight the specified item in the ListView, however it behaves as if the user was holding their finger down on the ListView item (I can tell because whenever an item is selected there's a subtle background added to the item when clicked which persists throughout when selected programmatically) and as soon as I touch the device's screen anywhere, the selected item is no longer selected (highlighted). I simply want to set the item as if it were a regular finger tap.

Thanks in advance.

UPDATE

Found an alternate solution. I simply tap the first item in my ListView programmatically by doing this.

Ivan
  • 665
  • 2
  • 10
  • 28

0 Answers0