-1
我有一個表格佈局,表格行從數據庫中動態添加。我需要以編程方式選擇只有一個錶行,並取消選擇以前的選擇。類似於ListView onItemClick。出於某些原因,我無法使用ListView。只選擇一個表格行並取消選擇其他
我有一個表格佈局,表格行從數據庫中動態添加。我需要以編程方式選擇只有一個錶行,並取消選擇以前的選擇。類似於ListView onItemClick。出於某些原因,我無法使用ListView。只選擇一個表格行並取消選擇其他
您可以在表格行上添加單擊偵聽器。請參閱下面的代碼:
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);
}
}