我有一个表格布局,表格行是从数据库中动态添加的。我需要以编程方式只选择一个表行并取消选择以前的选择。类似于listview onItemClick。由于某些原因,我不能使用ListView。
答案 0 :(得分:0)
您可以在表格行上添加点击侦听器。请参阅以下代码:
private int selectedIndex = -1;
private TableLayout tableLayout;
private void initTableLayout() {
View.OnClickListener clickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Integer index = (Integer) v.getTag();
if (index != null) {
selectRow(index);
}
}
};
tableLayout = (TableLayout) findViewById(R.id.table_layout);
final TableRow tr = new TableRow(this);
tr.setTag(0);
tr.setOnClickListener(clickListener);
// Add views on tr
tableLayout.addView(tr, 0, new TableLayout.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
final TableRow tr2 = new TableRow(this);
tr2.setTag(1);
tr2.setOnClickListener(clickListener);
// Add views on tr2
tableLayout.addView(tr2, 1, new TableLayout.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
....
}
private void selectRow(int index) {
if (index != selectedIndex) {
if (selectedIndex >= 0) {
deselectRow(selectedIndex);
}
TableRow tr = (TableRow) tableLayout.getChildAt(index);
tr.setBackgroundColor(Color.GRAY); // selected item bg color
selectedIndex = index;
}
}
private void deselectRow(int index) {
if (index >= 0) {
TableRow tr = (TableRow) tableLayout.getChildAt(index);
tr.setBackgroundColor(Color.TRANSPARENT);
}
}