Android : Programatically make TextView background color change while pressed

on Sunday, July 6, 2014


I have some TextViews which are dinamically added to a LinearLayout. These TextViews are clickable and have an onLongClickListener (I also intend to add onClickListener later)


Here is the thing, I want these TextView to change their background color when pressed and I read that you can use selectors to do such thing.


So I made this xml file in res/color/text_view_pressed.xml:



<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:color="#000000"/>
<item android:state_pressed="false"
android:color="#FFFFFF"/>
</selector>


I tried to create a TextView and using this xml file likes this:



TextView t = new TextView(this);
t.setBackgroundColor(R.color.text_view_pressed);


But when I do this, it will give this error in t.setBackgroundColor: "Should pass resolved color instead of resource id here: getResources().getColor(R.color.text_view_pressed)" but it doesn't work as intended if I use getResources().getColor(R.color.text_view_pressed).


Anyone got an idea how to do it?


0 comments:

Post a Comment