我有一個TableLayout和一些基於數據庫內容生成的未知數的TableRows。TableLayout中表行的索引
每行都有一個OnClick偵聽器,但是,一旦發生點擊事件,我無法告訴(有意義)它來自哪一行。有沒有一種方法可以獲得TableLayout相關的表格的索引,還是我應該嘗試其他的東西?
一些代碼:
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);
}
}
你弄混了變量,入口不是表格行。我剛剛進入Entry項目作爲標籤。 – Malfist
您應該閱讀旁邊的內容,並考慮將標記設置爲索引。這會導致對可能希望稍後收集垃圾回收的數據對象的更少可能的雜散引用,並且整體而言,更好地完善了編程實踐。 –