循环里面调用索引-小记

在循环里使用索引时要注意一些细节。如下:

TableLayout tableLayout = (TableLayout)view.findViewById(R.id.carNumberRfidTable);
int num=tableLayout.getChildCount();
for (int i=1;i<tableLayout.getChildCount();i++){
tableLayout.removeView(tableLayout.getChildAt(i));
}
使用for循环索引”i“是一直+1没什么问题,但是在某一次循环里调用了索引”i“,
移除了tableLayout的一个子view,这时候tableLayout的子view数量改变,
再次循环调用索引”i“,就不能获取到原来的子view,还可能造成数组索引异常,
可以尝试用while循环,如下:
while (num>1){
tableLayout.removeView(tableLayout.getChildAt(num-1));
num--;
}
posted @ 2017-10-30 15:15  风如故  阅读(211)  评论(0编辑  收藏  举报