9

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>
Halil Ozel
  • 2,482
  • 3
  • 17
  • 32
ab11
  • 19,770
  • 42
  • 120
  • 207

4 Answers4

23

Set this to your TextView:

android:clickable="true"
Ahmad
  • 69,608
  • 17
  • 111
  • 137
  • 1
    Interesting how my answer was posted earlier, but did not get accepted. Hmm. – Paul Burke Nov 08 '12 at 22:34
  • @PaulBurke Yes, I'm also wondering. But in my defense, I did not see that there was an other answer at the time I posted mine. I'm guessing ab11 did'nt notice which answer was posted earlier. But I did upvote yours. – Ahmad Nov 08 '12 at 22:40
  • 2
    No worries. Obviously not your fault (I actually intended to comment on the question). Thanks for the upvote! :-) – Paul Burke Nov 08 '12 at 22:53
9

Add

android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true"
Paul Burke
  • 25,496
  • 9
  • 66
  • 62
4

the above about setting clickable to true is correct. Additionally, if you add a onClickListener Android sets clickable to true for you automatically.

// From the View class.
public void setOnClickListener(OnClickListener l) {
    if (!isClickable()) {
        setClickable(true);
    }
    getListenerInfo().mOnClickListener = l;
}
user123321
  • 12,593
  • 11
  • 52
  • 63
0

The accepted answer is outdated. Adding android:clickable="true" to TextView XML will not work now. Instead, add the following attribute to the TextView XML code.

android:background="?android:attr/selectableItemBackground"
RusArtM
  • 1,116
  • 3
  • 15
  • 22