在我的 Android 应用程序中,有一个在运行时加载的表格布局。我为表行设置了 OnClickListener。
tr.setClickable(true);
tr.setOnClickListener(trOnClickListener);
我需要在单击表行时更改其背景颜色。这是我的 onClick 方法。
private OnClickListener trOnClickListener = new OnClickListener() {
public void onClick(View v) {
TableRow tablerow = (TableRow)v;
tablerow.setBackgroundDrawable(getResources().getDrawable(
R.drawable.ab_stacked_solid_whiteaction));
}
};
当我单击表格行时,它会更改背景颜色。当我单击另一行时,它也会更改其背景颜色。但我想要的是, 一次只能更改一行的背景颜色。
我怎样才能做到这一点?如有任何建议,我们将不胜感激。
提前致谢
最佳答案
在drawable文件夹中创建XML并将其设置为bg
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/cell_shape_in_white" android:state_pressed="true"/>
<item android:drawable="@drawable/cell_shape_in_grey"/>
</selector>
或者
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/cell_shape_in_white" android:state_focused="true" android:state_pressed="false"/>
<item android:drawable="@drawable/cell_shape_in_white" android:state_focused="true"/>
<item android:drawable="@drawable/cell_shape_in_grey" android:state_focused="false"/>
<item android:drawable="@drawable/cell_shape_in_grey"/>
</selector>
或者
引用链接How to change the background color of a TableRow when focused?
关于java - 安卓 : Change background color of table rows when it is clicked,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19995385/