Rodrigo
Rodrigo

Reputation: 100

Programatically make TextView background color change while pressed

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/drawable/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.drawable.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?

Upvotes: 2

Views: 1004

Answers (1)

matiash
matiash

Reputation: 55350

You are on the right track. However there is an important detail.

There are two types of resources that can be affected by states: ColorStateList and StateListDrawable.

A color state list can only be used in certain contexts, for example in TextView.setTextColor(). As far as I can see, you cannot use a color state list as parameter of setBackgroundColor() if you want to change the background of a View when it's pressed. You need a state list drawable for that. And in a state list drawable, the android:drawable attribute is mandatory.

So, to sum up:

  • The xml file should be placed in res\drawable,
  • Its structure should be slightly different (i.e. state list, not color list), and
  • You need to use setBackgroundResource() instead of setBackgroundColor().

Example file:

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

If you want to use custom colors instead of white and black, you simply need to define them as resources in res\values and reference them from here.

Upvotes: 2

Related Questions