Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to use selector for background of a TextView?

Tags:

android

I would like my TextView to paint with a different color background when pressed. The below xml contains a Button and TextView, both of which specify a Selector as their background. The Button works as expected, but the TextView does not change color when pressed. Is there a way to make this work for the TextView?

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView 
        android:text="temporary text view"
        android:layout_width="wrap_content"
        android:layout_height="100dip"
        android:background="@drawable/blackselector"
        />    
    <Button
        android:text="temporary button"
        android:layout_width="wrap_content"
        android:layout_height="100dip"
        android:background="@drawable/blackselector"
        />   
</LinearLayout>

selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <color android:color="#FF0000" />
    </item>
    <item>
        <color android:color="#00FF00" />
    </item>
</selector>
like image 644
ab11 Avatar asked Nov 08 '12 21:11

ab11


People also ask

What is ColorStateList?

A ColorStateList is an object you can define in XML that you can apply as a color, but will actually change colors, depending on the state of the View object to which it is applied.

What is selector in Android xml?

A selector can be an xml file created inside the drawable folder. Selector for different background colors. The following selector file btn_bg_selector. xml contains the code for setting different background colors on a button for different states.

What is Selector tag android?

A selector tag basically looks for the state of the UI at the time and displays the appropriate image. This particular drawable is for a check box, when the checkbox is in the state android:state_checked="false" (i.e. when the checkbox is not checked)


1 Answers

Set this to your TextView:

android:clickable="true"
like image 143
Ahmad Avatar answered Oct 24 '22 16:10

Ahmad