OnClick change tablerow background color

Joshua Sutherland picture Joshua Sutherland · Dec 10, 2010 · Viewed 19.7k times · Source

So I'm trying to find an easy way to get the background color or a table row to change when its clicked on. I've been trying to find a way to call what the background color is and check it but I haven't found a way to call the color. Here is what I have right now.

    RowName = (TableRow) findViewById(R.id.RowName); 
    RowName.setBackgroundColor(Color.TRANSPARENT);

    RowName.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            if (RowName.equals(Color.TRANSPARENT))
            RowName.setBackgroundColor(Color.YELLOW);

            else if (RowName.equals(Color.YELLOW))
            RowName.setBackgroundColor(Color.TRANSPARENT);
        }
    });

I know that its wrong. Hopefully you can see what I'm trying to accomplish. If not, what I want to do is have the table row start of transparent. When someone clicks on the table row I want it to change to yellow. Then, if they click it again, I want it to change back to transparent. Thanks.

Answer

Josh Clemm picture Josh Clemm · Dec 10, 2010

You need to set the background color of your row to a state list drawable (that handles select, pressed, active, non-active).

http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList

The XML should look something like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!--  Active state -->
    <item android:state_selected="true" android:state_focused="false"
        android:state_pressed="false" android:drawable="@android:color/transparent" />
    <!--  Inactive state-->
    <item android:state_selected="false" android:state_focused="false"
        android:state_pressed="false" android:drawable="@android:color/transparent" />
    <!--  Pressed state-->
    <item android:state_pressed="true" android:drawable="@android:color/yellow" />
    <!--  Selected state (using d-pad) -->
    <item android:state_focused="true" android:state_selected="true"
        android:state_pressed="false" android:drawable="@android:color/yellow" />
</selector>