android getchild view,Android | Get all children elements of a ViewGroup

这个博客介绍了一种使用递归重新实现获取ViewGroup中所有子视图的算法。方法首先检查是否为叶节点,若是则返回包含该视图的列表。对于内部节点,遍历并递归获取每个子视图的列表,最后合并所有子视图的列表。此外,还提供了一个辅助方法来排除父视图,仅返回子视图。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I've reimplemented this method in a recursive way. Not sure it's faster than MH's, but at least it has no duplicates.

private List getAllViews(View v) {

if (!(v instanceof ViewGroup) || ((ViewGroup) v).getChildCount() == 0) // It's a leaf

{ List r = new ArrayList(); r.add(v); return r; }

else {

List list = new ArrayList(); list.add(v); // If it's an internal node add itself

int children = ((ViewGroup) v).getChildCount();

for (int i=0;i

list.addAll(getAllViews(((ViewGroup) v).getChildAt(i)));

}

return list;

}

}

MH's answer includes the parent view which is being given to the method, so I created this auxiliary method (which is the one to be called).

I mean, if you call this method on a TextView (which has no children), it returns 0 instead of 1.

private List getAllChildren(View v) {

List list = getAllViews(v);

list.remove(v);

return list;

}

TLDR: to count all children copy and paste both methods, call getAllChildren()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值