Android动态TableRow获取视图数量及判断是否已满的解决方案
解决Android TableRow判断子视图数量的问题
嘿,这个问题我之前做动态表格布局的时候也碰到过!其实TableRow本身继承自ViewGroup,而ViewGroup提供了一个getChildCount()方法,正好能帮你获取当前TableRow里的子视图总数,完全满足你的需求~
具体实现思路:
- 先拿到你当前正在操作的TableRow实例
- 调用
getChildCount()获取它的子视图数量 - 判断数量是否达到10,达到的话就创建新的TableRow并添加到TableLayout中
给你写个简单的代码示例参考:
// 先获取你的TableLayout实例 TableLayout tableLayout = findViewById(R.id.your_table_layout); // 拿到当前正在填充的最后一行TableRow TableRow currentRow = (TableRow) tableLayout.getChildAt(tableLayout.getChildCount() - 1); // 获取当前行的子视图总数 int childCount = currentRow.getChildCount(); if (childCount >= 10) { // 创建新的TableRow currentRow = new TableRow(this); // 给新行设置布局参数(按需调整) currentRow.setLayoutParams(new TableRow.LayoutParams( TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT )); // 将新行添加到表格里 tableLayout.addView(currentRow); } // 接下来把你要添加的视图放到currentRow里 TextView newItemView = new TextView(this); newItemView.setText("你的内容"); currentRow.addView(newItemView);
额外补充:
getChildCount()会统计TableRow下所有直接子View,不管是TextView、ImageView还是自定义View都算在内,完全符合你的计数要求- 如果你需要删除视图,也可以用这个方法判断删除后当前行是否为空,进而做一些清理操作
内容的提问来源于stack exchange,提问作者Youcef LAIDANI
相关产品推荐
相关产品推荐

