bukka.wh bukka.wh - 1 year ago 204
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 Source

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

first put this in your listview


Then create xml files in drawable to control the diferent states


<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"/>


<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:angle="90" />


<shape xmlns:android="http://schemas.android.com/apk/res/android"
      android:angle="90" />

In your ListView Selection

listView.setOnItemClickListener(new OnItemClickListener() {

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download