How to click an specific TableRow within a TableLayout

倖福魔咒の 提交于 2019-12-02 04:32:23

问题


I made my own compound control that display a data grid using TableLayout and adding programmatically Tablerows within a loop depending of the Array of Object that im binding to it and now i want to select an specific row with its specific data in order to be used by a method. So how can i select an specific row retrieving its data to delegate a method?


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/11336117/how-to-click-an-specific-tablerow-within-a-tablelayout

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