Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 202
bukka.wh Avatar asked Jan 21 '14 08:01

bukka.wh


1 Answers

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.

like image 132
T.V. Avatar answered Oct 01 '22 19:10

T.V.