c4207c
c4207c

Reputation: 29

listView items to stay highlighted after being clicked

I have a ListView that I want the clicked item to have a background color to indicate which item is currently selected. I have achieved that by specifying a selector field

<ListView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:id="@+id/sub_arguments_listView"
    android:layout_weight="1"
    android:listSelector="@drawable/list_selector"
    android:choiceMode="singleChoice"
    android:clickable="true"/>

And the list_selector.xml is:

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

I have added a ListView.onItemClickListener():

 public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
   String text ="sometext";
    ((TextView)mMainView.findViewById(R.id.sub_argument_text)).setText(text);
}

This works fine and as expected as long as the variable "text" has a short contents. The problem I am having is when the contents of the variable "text" is a long text then the TextView is updated fine but the selected item in the ListView will loose the background (back to transparent) for some reason (my guess is the focus is lost). If I click on the same item again then the background stays and the item is still highlighted. Also please note that I have two Android devices:

  1. A Marshmallow 5.0 which is a fast device. And I don't see the issue.
  2. The second is a 4.2 and relatively slow device which shows this issue.

What am I missing ? How do I made the clicked item in the listView to remain highlighted all the time until another item is clicked ?

Thanks

Upvotes: 2

Views: 1442

Answers (2)

Arjun saini
Arjun saini

Reputation: 4182

You can try this Example...

Android ListView. How to change background color of manually selected item

also see this answer also

Change background color of selected item on a ListView

In your code

listView.setOnItemClickListener(new OnItemClickListener() {

     @Override
     public void onItemClick(AdapterView<?> parent, View view, int position,long arg3) {
         view.setSelected(true);
         ...
     }
}

Upvotes: 1

Sathish Kumar J
Sathish Kumar J

Reputation: 4335

Try this,

 public void onItemClick(AdapterView<?> parent, View view, int position, long id)
     {

       listView.setItemChecked(position, true);

     }

This may helps you.

Upvotes: 2

Related Questions