在我的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));
}
};
单击表格行时,会更改背景颜色。当我点击另一行时,它也会改变它的''背景颜色。但我想要的是, 应该一次改变一行的背景颜色。
我该怎么做?任何建议都表示赞赏。
提前致谢
答案 0 :(得分:1)
在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>
OR
<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>
OR
请参阅链接How to change the background color of a TableRow when focused?
答案 1 :(得分:1)
当选择并突出显示(黄色)其他行时,此非xml修复会导致先前选定的行恢复为中性表背景颜色(Lt。灰色)。这是通过引用所选(子)行的适当索引号来实现的。
public class dataTable extends Fragment {
TextView tvSelectedRow = null;
...
row.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
if(tvSelectedRow == null) {
iRowNumber = tableLayout.indexOfChild(v); //This returns the rowID of the selected row
tableLayout.setBackgroundResource(R.color.LtGrey); //sets background color to LtGray for whole table.
row.setBackgroundResource(R.color.yellow);//changes background color of selected row to yellow.
}else if(tvSelectedRow != null){
tableLayout.getChildAt(iRowNumber).setBackgroundResource(R.color.LtGrey);//causes previously selected row to revert to LtGray.
iRowNumber = tableLayout.indexOfChild(v); //Resets iRowNumber to new row selected by user....
row.setBackgroundResource(R.color.yellow);//changes background color of selected row to yellow.
}
}
});
祝你好运!
答案 2 :(得分:0)
试试这个
private View pressedView = null;
private OnItemClickListener getStartedListItem = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
Intent myintent = new Intent(getApplicationContext(),GetStartedWebview.class);
myintent.putExtra("SelectedItem", getStartedItems[position]);
startActivity(myintent);
if(pressedView != null) {
pressedView.setBackgroundResource(..); // reset background of old item
pressedView = arg1; // Point pressedView to new item
}
}
};