尝试在Android中的表格布局上触发事件时遇到了一些问题。这些是我用来动态填充表格布局的代码:
private void BuildTable() {
try {
DatabaseAdapter mDbHelper = new DatabaseAdapter(Category.this);
mDbHelper.open();
CategoryController cc = new CategoryController(mDbHelper.open());
Cursor mCur = mDb.rawQuery(cc.getAllCat(), null);
if (mCur.getCount() != 0) {
if (mCur.moveToFirst()) {
// Setting table header
TableRow row = new TableRow(this);
row.setLayoutParams(new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
do {
int cols = mCur.getColumnCount();
row = new TableRow(this);
for (int j = 1; j < cols; j++) {
// Dynamically load data fetch from database
// into table layout
TextView tv = new TextView(this);
tv.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
tv.setPadding(5, 5, 10, 5);
tv.setGravity(Gravity.LEFT);
tv.setText(mCur.getString(j));
row.addView(tv);
row.setId(j);
}
row.setClickable(true);
row.setOnClickListener(tablerowOnClickListener);
table_layout.addView(row);
} while (mCur.moveToNext());
}
}
} catch (SQLException mSQLException) {
throw mSQLException;
}
}
这是我的表格行onClickListener:
private OnClickListener tablerowOnClickListener = new OnClickListener() {
public void onClick(View v) {
//Highlight selected row
v.setBackgroundColor(getResources().getColor(android.R.color.holo_red_light));
final int k = v.getId();
Toast.makeText(Category.this, Integer.toString(k),
Toast.LENGTH_SHORT).show();
}
};
我的问题是当我突出显示某一行并再次选择另一行时,前一个突出显示的行仍然是相同的突出显示的背景颜色。我想知道如何解决它?
提前致谢。
答案 0 :(得分:2)
如果table_layout
与tablerowOnClickListener
的范围相同,请更改监听器,如下所示:
private OnClickListener tablerowOnClickListener = new OnClickListener()
{
public void onClick(View v)
{
//Highlight selected row
for (int i = 0; i < table_layout.getChildCount(); i++)
{
View row = table_layout.getChildAt(i);
if (row == v)
{
row.setBackgroundColor(getResources().getColor(android.R.color.holo_red_light));
}
else
{
//Change this to your normal background color.
row.setBackgroundColor(getResources().getColor(android.R.color.transparent));
}
}
//...
}
};