Android: Change table row color when it clicks and remove the color when click anothe row of the table

StackOverflow https://stackoverflow.com/questions/19998458

  •  30-07-2022
  •  | 
  •  

Question

In my android app there is a table layout which is loading at run time. I've implemented a code to change background color of this table when the row is clicked.

private OnClickListener trOnClickListener = new OnClickListener() {
    public void onClick(View v) {
        TableRow tablerow = (TableRow)v;

        tablerow.setBackgroundDrawable(getResources().getDrawable(
                R.drawable.table_row_selector));


    }
};

Now I want to remove this color when the user clicks another row of the table and newly clicked row should change it's color.

This is my drawable.

<?xml version="1.0" encoding="utf-8"?>

<item android:drawable="@drawable/ab_stacked_solid_whiteaction" android:state_pressed="true"/>
<item android:drawable="@drawable/table_shape" android:state_enabled="true"/>

Any suggestions are highly appreciated.

Thanx in advcance

Was it helpful?

Solution

Change your drawable to look something like this

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

    <item android:drawable="@drawable/background_selectable" android:state_pressed="false"/>
    <item android:drawable="@drawable/background_selectable" android:state_focused="false"/>
    <item android:drawable="@drawable/background_selectable" android:state_selected="false"/>
    <item android:drawable="@drawable/background_selectable" android:state_active="false"/>
</selector>

Then you set your row to tablerow.setSelected(true). When another row is selected, set the previous selected row to tablerow.setSelected(false) and the newly selected row to true

I use this in one of my ListViews and it works.

Hope this helps

OTHER TIPS

If you are doing from xml use selectors, and apply as background or source..

Create a field: View restoredView

row.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (restoredView != null) {
            restoredView.setBackgroundColor(Color.parseColor("#EEEEEE"));
        }
        view.setBackgroundColor(Color.parseColor("#DDDDDD"));
        restoredView = view;
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top