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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With