bukka.wh bukka.wh - 4 months ago 85
Android Question

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

Can You help me please. I need to change background color of my list view item which is selected manually by setSelection(int pos) function and I need to stay with new color until new setSelection call. I have read some topics of how to do this, but I still have no succes. Thanks!

Answer

I've managed to accomplish that by making several selectors for the different states

first put this in your listview

android:listSelector="@drawable/list_selector"

Then create xml files in drawable to control the diferent states

@drawable/list_selector

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/list_item_bg_normal" android:state_activated="false"/>
<item android:drawable="@drawable/list_item_bg_pressed" android:state_pressed="true"/>
<item android:drawable="@drawable/list_item_bg_pressed" android:state_activated="true"/>
</selector>

@drawable/list_item_bg_normal

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
  android:startColor="@color/list_background"
  android:endColor="@color/list_background"
  android:angle="90" />
</shape>

@drawable/list_item_bg_pressed

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
  <gradient
      android:startColor="@color/list_background_pressed"
      android:endColor="@color/list_background_pressed"
      android:angle="90" />
</shape>

In your ListView Selection

listView.setOnItemClickListener(new OnItemClickListener() {

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

Don't forget to add list_background_pressed and list_background to your values/color.xml or just set the color manually in each file.

And I Believe that when you use setSelection(int pos) that will automatically uset the layout you've set as selectected.

Hope it helps.