Set a background color to a selected ListView Item in android Set a background color to a selected ListView Item in android android android

Set a background color to a selected ListView Item in android


  1. To highlight the selected item, you should request focus for the listView and run setSelection() in the UI thread. This worked for me:
runOnUiThread(new Runnable() {    public void run() {        myList.requestFocus();        myList.setSelection(position);    }});

2.To apply a specific color to an item. You can use customized listItem.

a. Set customized lisItem for your listView:

ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this, R.layout.customizedlistitem,arrListView);myList.setAdapter(listAdapter);

b. In your layout folder, create customizedlistitem.xml

<TextView xmlns:android="http://schemas.android.com/apk/res/android"      android:id="@+id/customizedlistitem"       android:layout_width="match_parent"       android:layout_height="wrap_content"    android:background="@drawable/customizedbackground"/>   

c. In your drawable folder, create customizedbackground.xml like this:

<selector xmlns:android="http://schemas.android.com/apk/res/android">    <item android:state_selected="true" android:state_pressed="false" android:drawable="@color/RED"></item>    <item android:state_pressed="true" android:drawable="@color/GREEN"></item>          <item android:drawable="@color/BLACK"></item>   <!-- for other state -->        </selector>

d. Make sure color RED, GREEN and BLACK was defined in your project (you can define it in color.xml under values folder):

<?xml version="1.0" encoding="utf-8"?><resources>       <color name="RED">#FF0000</color>     <color name="GREEN">#008000</color>     <color name="BLACK">#000000</color></resources>


Try this, it will work-

myList.getChildAt(myList.getSelectedItemPosition()).setBackgroundColor(Color.RED);


ListView in xml file:

<ListView android:id="@+id/android:list" android:layout_width="fill_parent"        android:layout_height="wrap_content"         android:layout_below="@+id/Tablayoutdesign"        android:cacheColorHint="#000000"        android:dividerHeight="1dip"        android:layout_marginTop="63dip"        android:layout_marginBottom="40dip"        />

Create new xml with listselector name like:

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android">   <!-- Selected -->   <item     android:state_focused="true"     android:state_selected="false"     android:drawable="@drawable/focused"/>   <!-- Pressed -->  <item     android:state_selected="true"     android:state_focused="false"    android:drawable="@drawable/selected" /> </selector>

Create colors.xml file like:

<resources>    <drawable name="focused">#ff5500</drawable>    <drawable name="selected">#FF00FF</drawable></resources>

In your java code:

ListView lv= (ListView) findViewById(R.id.list);lv.setSelector( R.drawable.listselector);