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

11,603

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.

Share:
11,603
levkatata
Author by

levkatata

Updated on June 04, 2022

Comments

  • levkatata
    levkatata almost 2 years

    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.