How to get selected row object from Table in Android?

让人想犯罪 __ 提交于 2019-12-13 04:39:17

问题


I am using following code to create a table with 3 rows. Now, what I need is whenever user selects a row I just want to Toast the value of selected row. This is a sample application, actually I have a vector and I am displaying the vector values in a tabular format. I want to implement some onItemSelected or some thing whenever user selects on a tablerow I need to get that object.

Can anyone help on this.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TableLayout table = (TableLayout) findViewById(R.id.TableLayout01);
       table.removeAllViews();

       String[] valuesList = {"1","2","3"};
       for(int i=0;i<3;i++)
       {
            TableRow row = new TableRow(this);
            // count the counter up by one
            row.setLayoutParams(new LayoutParams(100,100));
            // create a new TextView
            TextView t = new TextView(this);
            t.setTextColor(Color.BLACK);
            // set the text to "text xx"     
            String value = valuesList[i];
            t.setText(value);
            row.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                    view.setBackgroundColor(Color.DKGRAY);
                }
                });


            View v = new View(this);
            v.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 1));
            v.setBackgroundColor(Color.rgb(51, 51, 51));

            // add the TextView and the CheckBox to the new TableRow

            TableLayout.LayoutParams tableRowParams=
                      new TableLayout.LayoutParams
                      (TableLayout.LayoutParams.FILL_PARENT,200);

                    int leftMargin=10;
                    int topMargin=5;
                    int rightMargin=10;
                    int bottomMargin=5;

            tableRowParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);

            row.setLayoutParams(tableRowParams);
            row.addView(t);

            // add the TableRow to the TableLayout
            table.addView(row);//,new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            table.addView(v);
       }
}

Thank you.


回答1:


You may need to do this:

 row.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                 Toast.makeText(getApplicationContext(), "value was "+value, 
                  Toast.LENGTH_LONG).show();
                    view.setBackgroundColor(Color.DKGRAY);
                }
                });


来源:https://stackoverflow.com/questions/15380457/how-to-get-selected-row-object-from-table-in-android

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