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

六眼飞鱼酱① 提交于 2019-12-01 04:08:18

问题


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:


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.



来源:https://stackoverflow.com/questions/3345189/android-tablerow-how-to-add-view-dynamically-to-certain-postion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!