I have a table layout with table rows being added dynamically from the database. I need to programmatically choose only one table row and deselect the previous choosen. Similar to a listview onItemClick. For some reasons I can't use a ListView.
Asked
Active
Viewed 797 times
1 Answers
0
You could add click listener on table rows. See the code below:
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);
}
}

David Rauca
- 1,583
- 1
- 14
- 17