I'm creating tablerows programmatically, and I'm trying to implement an OnClickListener:
final TableRow tr = new TableRow(this);
tr.setId(tourney.getColumnIndex("_id"));
tr.setClickable(true);
tr.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
v.setBackgroundColor(Color.GRAY);
System.out.println("Row clicked: " + v.getId());
}
}开发者_StackOverflow);
But everytime I click on the row, I get a value of -1. Why am I not getting the id that I set?
Your TableRow object is conforming to OOP standards, it should only be aware of it´s own state, not it´s position in another object. Instead, you should grab a reference to your TableLayout, and then call indexOfChild(View child)
on it:
TableLayout tblLayout = (TableLayout) findViewById(R.id.yourTableLayout);
int tableRowIndex = tblLayout.indexOfChild(tr);
The reason why I was getting -1 on getId was because of this line:
tr.setId(tourney.getColumnIndex("_id"));
"_id" was not a part of the query, so I was not getting the column index. Even then, it wasn't the value I really wanted, but this fixed my issue:
tr.setId(tourney.getInt(tourney.getColumnIndex("_id"));
精彩评论