Pallavi Pallavi - 19 days ago 7
Android Question

How to get click event of table row/ table item?

I have a simple table layout in the .xml file. I am adding components to it at run-time.
Following is my code:

public class Home extends Activity{

TextView tv1; int i;TableRow tbrow;
String [] names = {"First Name","Last Name", "Title","Company","Phone"};
int [] images = { R.drawable.icon,R.drawable.icon,R.drawable.star2,R.drawable.icon,R.drawable.icon}


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TableLayout ll=(TableLayout) findViewById(R.id.tableLayout1);


TableRow trow=new TableRow(this);
ImageView Image1=new ImageView(this);
ImageView Image2=new ImageView(this);
ImageView Image3=new ImageView(this);
ImageView Image4=new ImageView(this);
tv1=new TextView(this);
trow.setClickable(true);

Image1.setImageResource(R.drawable.blank);
Image2.setImageResource(R.drawable.star2);
Image3.setImageResource(R.drawable.blank);
Image4.setImageResource(R.drawable.blank);

tv1.setText("Brochures");
trow.addView(Image1);
trow.addView(tv1);
trow.addView(Image2);
trow.addView(Image3);
trow.addView(Image4);
trow.setId(0);
ll.addView(trow);
for(i=1;i<5;i++){
tbrow=new TableRow(this);
ImageView img1=new ImageView(this);
tv1=new TextView(this);
CheckBox chk=new CheckBox(this);
ImageView img2=new ImageView(this);
ImageView img3=new ImageView(this);
img1.setImageResource(R.drawable.pdf);
img2.setImageResource(R.drawable.blank);
img3.setImageResource(R.drawable.blank);

tv1.setText(""+names[i]);
tbrow.addView(img1);
tbrow.addView(tv1);
tbrow.addView(chk);
tbrow.addView(img2);
tbrow.addView(img3);
tbrow.setId(i);
Log.e("TAG", "ID: "+tbrow.getId());
tv1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Toast.makeText(Home.this, ""+tbrow.getId(),
Toast.LENGTH_SHORT).show();
Log.e("TAG", " clicked ID: "+tbrow.getId());
}
});
ll.addView(tbrow);
}
}
}


Whenever I click on any of the rows, the
onClick()
event of the last row is triggered. Instead of text view, I also tried to trigger the
onClick()
event for table row, but in vain.

I want to know which row is clicked.
getID()
,
setID()
won't work.

Please help.

Answer

Change the line

tbrow=new TableRow(this);

to

final TableRow tbrow = new TableRow(this);

and it will work as you expect.

Comments