How to keep fixed the color of the selected item

4

Adding the listener to Listview through the setOnItemClickListener method, each time you click on one of your items, it changes color momentarily. Is there any way to keep this color fixed on the item that is clicked?

    
asked by anonymous 10.07.2015 / 16:57

1 answer

2

1 - Add the attribute android:choiceMode to ListView ,

to allow you to select only one line:

android:choiceMode="singleChoice"

to allow you to select more than one line:

android:choiceMode="multipleChoice"

2 - Add the following attribute to the layout of the list item:

android:background="?android:attr/activatedBackgroundIndicator"

If you want to customize the appearance of the selection, in the res / drawable folder, create a selector

listselector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
   android:exitFadeDuration="@android:integer/config_mediumAnimTime">

   <item android:drawable="@android:color/holo_green_light" android:state_pressed="true"/>
   <item android:drawable="@android:color/holo_purple" android:state_selected="true"/>
   <item android:drawable="@android:color/holo_purple" android:state_activated="true"/>

</selector>

Change the colors to your liking!

The background attribute of the list item should be declared like this:

android:background="@drawable/listselector"

EDIT after comments

As you are using more than one color for the backgroud of the ListView rows, you need to set a Selector for each of them:

To assign the default background color an Selector item is created without State , this item must be the last of the Selector in>:

listselector_par.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
   android:exitFadeDuration="@android:integer/config_mediumAnimTime">

   <item android:drawable="@android:color/holo_green_light" android:state_pressed="true"/>
   <item android:drawable="@android:color/holo_purple" android:state_selected="true"/>
   <item android:drawable="@android:color/holo_purple" android:state_activated="true"/>

    <!-- cor do fundo quando não seleccionada (cor por defeito) -->
    <item android:drawable="@android:color/holo_green_dark"/>
</selector>

Create another Selector , listselector_impar.xml , indicated another color for the background.

Adapter assigns the background its selector as the line is even or odd.

Note:
If you do not like the animation effect, delete the line:

android:exitFadeDuration="@android:integer/config_mediumAnimTime"

or change the value config_mediumAnimTime

    
10.07.2015 / 18:48