如何在TableLayout中单击特定的TableRow

ark*_*tal 2 android tablelayout tablerow xamarin.android

我创建了自己的复合控件,使用TableLayout显示一个数据网格,并在循环中添加Tablerows,取决于我绑定到它的Object数组,现在我想选择一个特定的行及其特定的数据,以便由一个方法.那么如何选择检索其数据的特定行来委托方法呢?

Par*_*shi 9

嗨你可以尝试这样的事情,

 // create a new TableRow

    TableRow row = new TableRow(this);
    row.setClickable(true);  //allows you to select a specific row

    row.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            v.setBackgroundColor(Color.GRAY);
            System.out.println("Row clicked: " + v.getId());

           //get the data you need
           TableRow tablerow = (TableRow)v.getParent();
           TextView sample = (TextView) tablerow.getChildAt(2);
           String result=sample.getText().toString();
        }
    });
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅Android TableRow


Al *_*ath 7

我尝试了Parth Doshi的回答并发现它不太正确.该view参数onClick是一个TableRow,所以当v.getParent()被调用时,它返回一个TableLayout对象,因此它铸造时会抛出异常TableRow.因此,适合我的代码是:

tableRow.setClickable(true);  //allows you to select a specific row

tableRow.setOnClickListener(new OnClickListener() {
      public void onClick(View view) {
        TableRow tablerow = (TableRow) view; 
        TextView sample = (TextView) tablerow.getChildAt(1);
        String result=sample.getText().toString();

        Toast toast = Toast.makeText(myActivity, result, Toast.LENGTH_LONG);
        toast.show();
    }
});
Run Code Online (Sandbox Code Playgroud)