Reputation: 3160
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
Upvotes: 0
Views: 959
Reputation: 105
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;
}
});
Upvotes: 0
Reputation: 7081
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
Upvotes: 1
Reputation: 757
If you are doing from xml use selectors, and apply as background or source..
Upvotes: 0