我动态地创建了一个表格行,其中包含三个textviews.now我想在tablerow(tr)上点击三个textview的值。我想要获得companyTV,valueTV& YearTV的价值。 感谢。
for (int i = 0; i < match.length; i++) {
/** Create a TableRow dynamically **/
tr.setBackground(getResources().getDrawable(R.drawable.tv_bg));
tr = new TableRow(this);
tr.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.FILL_PARENT,
TableRow.LayoutParams.FILL_PARENT));
/** Creating a TextView to add to the row **/
companyTV = new TextView(this);
companyTV.setText(match[i]);
companyTV.isClickable();
companyTV.setTextColor(Color.RED);
companyTV.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
companyTV.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
companyTV.setPadding(5, 5, 5, 5);
tr.addView(companyTV); // Adding textView to tablerow.
/** Creating another textview **/
valueTV = new TextView(this);
valueTV.setText(kanr[i]);
valueTV.isClickable();
valueTV.setTextColor(Color.RED);
valueTV.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
valueTV.setPadding(5, 5, 5, 5);
valueTV.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
tr.addView(valueTV); // Adding textView to tablerow.
YearTV = new TextView(this);
YearTV.setText(ort[i]);
YearTV.setTextColor(Color.RED);
YearTV.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
YearTV.setPadding(5, 5, 5, 5);
YearTV.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
tr.addView(YearTV); // Adding textView to tablerow.
// Add the TableRow to the TableLayout
tl.addView(tr, new TableLayout.LayoutParams(
TableRow.LayoutParams.FILL_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
}
答案 0 :(得分:3)
首先,在创建表格行的背景之前,代码中有一个错误。您应首先创建新表行,然后设置其背景:
for (int i = 0; i < match.length; i++) {
/** Create a TableRow dynamically **/
tr = new TableRow(this);
tr.setBackground(getResources().getDrawable(R.drawable.tv_bg));
您可以在OnClickListener
tr.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
TableRow tr = (TableRow)v;
TextView companyTV, valueTV, yearTV;
String company, value, year;
companyTV = (TextView) tr.getChildAt(0);
valueTV = (TextView) tr.getChildAt(1);
yearTV = (TextView) tr.getChildAt(2);
company = companyTV.getText().toString();
value = valueTV.getText().toString();
year = yearTV.getText().toString();
}
});
如果要跟踪当前选择的表行,可以为活动创建全局变量
TableRow selectedTR;
然后在OnClickListener
selectedTR = (TableRow)v;
当您使用selectedTR
变量时,请确保在没有选择的情况下检查它是否为空值。