如何从表行获取TextView id

时间:2014-12-20 07:55:43

标签: java android android-tablelayout

我绘制桌面,然后是桌子。在每个表格单元格中我都有TextView,那么当用户点击它时,如何获取它的ID或其他数字呢?

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

    TableLayout lTableLayout;
    lTableLayout = (TableLayout) findViewById(R.id.tbLayout);

    /*Draw table top*/
    TableRow trTop = new TableRow(this);
    trTop.setPadding(0, 5, 0, 0);
    trTop.setBackgroundColor(Color.rgb(102, 178, 255));
    lTableLayout.addView(trTop, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    String[] str = new String[]{"Time", "Room1", "Room2"};
    for(int j=0; j<3; j++){
        TextView tv1 = new TextView(this);
        tv1.setPadding(2, 2, 2, 2);
        tv1.setTextSize(14);
        tv1.setText(str[j]);
        trTop.addView(tv1,LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
    }
    /*Draw table body*/
    for(int i=0; i<5; i++){

        final TableRow tr1 = new TableRow(this);
        tr1.setPadding(0, 5, 0, 0);



        if((i%2) == 0)
            tr1.setBackgroundColor(Color.WHITE);
        lTableLayout.addView(tr1, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        for(int j=0; j<3; j++){

            final TextView tv1 = new TextView(this);
            tv1.setPadding(2, 2, 2, 2);
            tv1.setTextSize(12);
            if(j==0){
                tv1.setText(8+i + ":00");
            }else{
                tv1.setText("reserved");
            }
            tr1.addView(tv1,LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
            tv1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    Toast.makeText(getApplicationContext(), "id = " + tv1.getId(),
                            Toast.LENGTH_LONG).show();
                    Log.e("TAG", " clicked ID: " + tr1.getId());
                }
            });
        }

    }

我在这里寻找id:

public void onClick(View arg0) {
                    Toast.makeText(getApplicationContext(), "id = " + tv1.getId(),
                            Toast.LENGTH_LONG).show();
                    Log.e("TAG", " clicked ID: " + tr1.getId());
                }
            });

但TOAST说:&#34; id = -1&#34;对于每个textview。

1 个答案:

答案 0 :(得分:0)

public void onClick(View arg0) {
                    Toast.makeText(getApplicationContext(), "id = " + tv1.getId(),
                            Toast.LENGTH_LONG).show();
                    Log.e("TAG", " clicked ID: " + tr1.getId());
                }
            });

好像你希望得到一个带有 tv1 .getId()的log.e(),并且它说 tr1 .getId(),所以你&& #39;获取表行Id而不是TextView Id。尝试将tr1更改为tv1并告诉我它是否有效。

编辑:

每次创建文本视图和表格行时,请使用tr1.setId(i)tv1.setId(j)手动为其分配ID。它应该有用。