我有一个TableLayout和一些未知数量的TableRows,它们是根据数据库中的内容生成的。
每一行都附加一个OnClick侦听器,但是,一旦发生单击,我无法(从内容)告诉它来自哪一行。有没有办法可以获得与TableLayout相关的tablerow索引,还是应该尝试其他的东西?
一些代码:
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);
}
}
答案 0 :(得分:8)
有同样的问题,这是解决方案:
row.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Current Row Index
int rowIndex = tableLayout.indexOfChild(v);
// Do what you need to do.
}
});
就我而言,我在TableRow中的TextView上有了Listener ...
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// The row the view is in
TableRow row = (TableRow) v.getParent();
// It's index
int index = tableLayout.indexOfChild(row);
}
});
答案 1 :(得分:3)
使用TableRow的标签:
BudgetEntryItem entry = null;
for(int i = 0; i < budgetItems; i++){
entry = budgetItems[i]; // or budgetItems.get(i), etc
TableRow tr = new TableRow(this);
// Set the index as the tag
tr.setTag(i); // or entry.setTag(entry.index()), etc
// ...
}
现在要获取索引,只需将其转换回onClick中的int,它将为您提供原始视图。
撇开
有些人不愿意以这种方式使用Tag,因为它将数据层与UI层耦合在一起。另一种方法是使用字典或词典等间接访问项目,而不将UI元素绑定到数据对象。
答案 2 :(得分:3)
试试这个,
row = new TableRow(this);
row.setId(i);
row.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast toast = Toast.makeText(getApplicationContext(), "Tabele row clicked "+ Integer.toString(v.getId()) , Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
}
});