How to click an specific TableRow within a TableLayout

∥☆過路亽.° 提交于 2019-12-02 00:24:27

hi you can try something like this,

 // 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();
        }
    });

For more info refer Android TableRow

I tried Parth Doshi's answer and found it to be not quite correct. The view parameter in onClick is a TableRow, so when v.getParent() is called, it returns a TableLayout object, and so an exception is thrown when casting it to TableRow. As such the code that works for me is:

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();
    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!