Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android TableRow - How to add View dynamically to certain postion?

I'm constructing TableLayout dynamically. And I need TableRow has a gap in certain column position.

For example, I need row has ImageView on 3 and 5 position, next row has ImageView on 1, 2, 4 position. I try to use:

   TableRow row1 = new TableRow(this);  
   row1.addView(new ImageView(this), 2);  
   row1.addView(new ImageView(this), 4);  
   mTable.addView(row1);
   TableRow row2 = new TableRow(this);  
   row2.addView(new ImageView(this), 0);  
   row2.addView(new ImageView(this), 1);  
   row2.addView(new ImageView(this), 3);
   mTable.addView(row2);

but I got IndexOfBoundException at Runtime.
ERROR/AndroidRuntime(771): Caused by: java.lang.IndexOutOfBoundsException: index=2 count=0

Any suggestions would be appreciated.
Thank you.

like image 212
levkatata Avatar asked Oct 14 '22 02:10

levkatata


1 Answers

Actually, the error seems quite logical at first glance on your code. Unless you table is created from xml and as the required number of rows, when you add a view at the index 2, this index does not exist. Try replacing this 2 by a 0, you will see that it works. So you just need to add empty ImageView the other indexes if you want to stick to yours.

like image 138
Sephy Avatar answered Oct 18 '22 14:10

Sephy