简体   繁体   中英

Android: Set TextView color on click like in the ListView

I have some textViews in my LinearLayout. They are clickable and I would like to make them onClick like for a ListView. For the listView, when the user clicks an item, the background becomes green I think.

I know that i can do this manually with

tv.SetBackgroundColor(Color.GREEN);

But is there something automaticaly to do this, like for the listView where the selection is managed automaticaly.

Thank you.

You need to define the background as a new XML file containing a list of states.

http://developer.android.com/guide/topics/resources/color-list-resource.html

For example, create a file called background_states.xml in your drawable folder and write something like this:

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:state_selected="true"
   android:drawable="@color/white" ></item>
<item
    android:state_pressed="true"
   android:drawable="@color/white" ></item>
<item 
    android:drawable="@color/black" /> 
</selector> 

Then define this new file as background in your TextView:

<TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:background="@drawable/background_states"

See the link above for more information about the different states.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM