I am developing a project in which I am required to change the color of text in a ListView on selecting the item of the ListView.
I can change the color of text on selecting the list item but, after a few seconds, the color changes back to what it was previously. I want that color unchanged until I click on another list item. Just look at the following screenshot:
I can get the changed color text in white on click of item of the ListView, but after a few seconds the text changes back to the previous color.
I want to keep the white color of the textview until I click to the other item of the ListView.
The following is my selector file for textviews. For Black text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:color="@android:color/white"/>
<item android:state_focused="true" android:color="@android:color/white"/>
<item android:state_selected="false" android:color="@android:color/black"/>
</selector>
For Red text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:color="@android:color/white"/>
<item android:state_focused="true" android:color="@android:color/white"/>
<item android:state_selected="false" android:color="@color/red"/>
</selector>
You need to store the position of the selected item somewhere and override the
getViewof the adapter so that the background is set correctly when recycling the views. Also you need to tell your adapter to refresh the views when the item gets selected.If you use
ArrayAdapteryou can for instance extend it like that:And when clicking an item you just need to call the
setSelectionmethod: