Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the selector of a layout to change its child's properties

By default, ListView changes background color to orange on being pressed and also the TextColor of TextView changes to white/black. By applying a selector on a ListView item we can set background color for pressed state but can we also define the TextColor for the TextView inside that item/layout within same selector? If so, then how?

like image 478
Umar Qureshi Avatar asked Nov 21 '11 11:11

Umar Qureshi


2 Answers

Amy88's answer resolved the problem, but doesn't specifically address changing a ViewGroup's child's properties.

Suppose you have a clickable LinearLayout with a TextView which should change color when pressed. The key is to use android:duplicateParentState="true" on the child views:

<LinearLayout
    android:duplicateParentState="true"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:duplicateParentState="true"
        android:text="@string/hello_world"
        android:textColor="@drawable/text_selector" />

</LinearLayout>

You can specify the selector as in Amy88's answer.

like image 127
Paul Lammertsma Avatar answered Sep 27 '22 21:09

Paul Lammertsma


If you are defining custom layout file for the ListAdapter, then set the text color of TextView in custom layout to an xml. This layout should be placed in a drawable resource folder (create a folder drawable and place the text_selector.xml in it).

text_selector.xml:

<item android:state_selected="true" android:color="@android:color/black"/>
<item android:state_focused="true" android:color="@android:color/black"/>
<item android:state_pressed="true" android:color="@android:color/black"/>
<item android:color="@android:color/white"/>

To set the text color use: android:textColor="@drawable/text_selector"

The above sample xml will set the text color to white by default and will set the text color to black when the list item is focussed, selected or pressed.

like image 37
Kannan Suresh Avatar answered Sep 27 '22 23:09

Kannan Suresh