Sergei Maslovskiy Sergei Maslovskiy - 27 days ago 13
Android Question

How get TextView id from table row

I draw table top and then table body. In each table cell I have TextView, so how can I get it's id or another number, when user clicked on it?

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

}


Here I'm looking for id:

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


But TOAST says : "id = -1" for each textview.

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

Seems like you're expecting to get a log.e() with tv1.getId() and it says tr1.getId(), so you're getting the Table row Id and not the TextView Id. Try changing tr1 to tv1 and tell me if it worked.

EDIT:

Everytime you create a textview and a table row, assign them Ids manually with tr1.setId(i) and tv1.setId(j). It should work with that.