I have a TableLayout and some unknown number of TableRows that are generated based on what’s in the database.
Every row has an OnClick listener attached, however, once the click happens I can’t tell (meaningfully) from what row it came from. Is there a way that I can get the index of the tablerow in relation to the TableLayout or should I try something else?
Some code:
private void buildBudgetTable() {
NumberFormat currencyFormatter = DecimalFormat.getCurrencyInstance();
TableLayout budgetTable = (TableLayout) findViewById(R.id.budgetTable);
budgetTable.removeAllViews();
try {
this.budgetItems = Budget.GetEntries(this);
} catch (SQLException e) {
Toast.makeText(getApplicationContext(), "Could not load budget", Toast.LENGTH_SHORT).show();
e.printStackTrace();
finish();
}
for(BudgetEntryItem entry : budgetItems){
TableRow tr = new TableRow(this);
tr.setPadding(1, 2, 1, 2);
TextView txtLeft = new TextView(this);
txtLeft.setText(entry.Memo);
txtLeft.setGravity(Gravity.LEFT);
txtLeft.setPadding(3,3,3,3);
TextView txtRight = new TextView(this);
txtRight.setText(currencyFormatter.format(entry.Amount));
txtRight.setGravity(Gravity.RIGHT);
txtRight.setPadding(3,3,3,3);
if(entry.Amount > 0){
txtRight.setBackgroundColor(Color.rgb(0x33, 0xEE, 0x33));
txtLeft.setBackgroundColor(Color.rgb(0x33, 0xEE, 0x33));
}else{
txtRight.setBackgroundColor(Color.rgb(0xEE, 0x33, 0x33));
txtLeft.setBackgroundColor(Color.rgb(0xEE, 0x33, 0x33));
}
tr.addView(txtLeft);
tr.addView(txtRight);
tr.setOnClickListener(this);
budgetTable.addView(tr);
}
}
Use the TableRow’s tag:
Now to grab the index, just convert it back to an int in your onClick which provides you with the originating View.
An aside
Some people frown on using Tag’s in this manner on the principle that it couples the data layer with the UI layer. An alternative would be to use a Dictionary or Dictionary, etc to access the item indirectly without tying the UI element to the data object.