OnClick change tablerow background color
Question
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.
Solution 2
So here is what wound up working. Make sure you have your TableRows named. Before my on create I have
private TableRow RowName;
I also have
int state = 0;
. I then add the code
public void RowName(View view) { switch (state) { case 0: RowName.setBackgroundColor(Color.YELLOW); state = 1; break; case 1: RowName.setBackgroundColor(Color.TRANSPARENT); state = 0; break; } }
To get it to work, go into your xml and in the OnClick property add RowName or the name of the public void that you are working with. Enjoy.
OTHER TIPS
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>