5

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.

levkatata
  • 53
  • 1
  • 1
  • 3

1 Answers1

4

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
  • 50,022
  • 30
  • 123
  • 131
  • 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 Jul 27 '10 at 16:01
  • 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 Jul 27 '10 at 16:11
  • 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 Jul 27 '10 at 16:25
  • 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 Jul 27 '10 at 17:18
  • Actually, GridView doesn't support addView operation for particular position. But thank you although) – levkatata Jul 28 '10 at 10:22