Change listview row item background color and text color in android

Mihir Shah picture Mihir Shah · Aug 8, 2013 · Viewed 8.7k times · Source

In my custom listview, I have used relativelayout and inside that added 2 textviews vertically. Background image is set to relativelayout. Now I want to change background image as well as textcolor of textview when listview item is pressed. How to do this, any one have idea?

Answer

Mihir Shah picture Mihir Shah · Aug 8, 2013
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/item_bg"
    android:orientation="vertical" >
    <TextView 
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text=""
    android:textColor="@color/orange"
    android:textSize="18sp"
    android:textStyle="bold"
    android:layout_marginTop="10dip"
    android:layout_marginLeft="10dip"
    />

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dip"
    android:layout_marginRight="20dip"
    android:layout_marginTop="8dip"
    android:ellipsize="end"
    android:maxLines="3"
    android:duplicateParentState="true"   <!-- this is a line to use..-->
    android:textColor="@color/_textcolor"
    android:textSize="14sp" >

</TextView>

item_bg.xml inside res/drawable folder:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true"  android:drawable="@drawable/bannerbg_hover"/>
<item android:state_focused="true"  android:drawable="@drawable/bannerbg_hover" />
<item android:state_selected="true" android:drawable="@drawable/bannerbg_hover"/>
<item android:drawable="@drawable/bannerbg"/>
</selector>

_textcolor.xml inside res/color/ folder:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true"  android:color="@color/white"/>
<item android:state_focused="true"  android:color="@color/white" />
<item android:state_selected="true" android:color="@color/white"/>
<item android:color="@color/dark_blue"/>
</selector>