Question

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?

Was it helpful?

Solution

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

OTHER TIPS

Concerning the background, you should create a StateList Drawable and set it as the background of your rows.

Ex of a such drawable (could be named background_selector.xml) :

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@color/color1" /> <!-- pressed -->
    <item android:drawable="@color/color2" /> <!-- default -->
</selector>

And in the layout declaration of your row :

...
android:background="@drawable/background_selector"
...

Use the same way for your text with the Color State List

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top