views:

350

answers:

1

Hello, friends!

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.

+1  A: 

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.

Sephy
Serhy, thank you for reply. But, maybe, you know how should I specify the quantity of columns in a row? Or quantity of rows and columns in a table? I just wanted to use addView(view, index) without such error...
levkatata
If I understand you properly, you want to have images in a cell, then not in the next, then one image, then not, ... and then in the next line, the opposite, starting with an empty cell?
Sephy
Yes, Serhy, you're right. But there are various of such layout I need create, like a rhombus, like a cross, like a tick and so on. I've tried your solution, it works great! But I've noticed, that time of creating such layout is increased depends on quantity of views I create. I have to create many empty views...
levkatata
in this case, maybe try to use a GridView? this will give you a grid, and you can define the number of rows/columns
Sephy
Actually, GridView doesn't support addView operation for particular position.But thank you although)
levkatata