1.递归方式
public static int getViewCountByRecursive(View root){
int viewCount = 0;
if (null == root){
return 0;
}
viewCount++;
if (root instanceof ViewGroup){
for (int i = 0; i < ((ViewGroup) root).getChildCount(); i++) {
View child = ((ViewGroup) root).getChildAt(i);
if (child instanceof ViewGroup){
viewCount += getViewCountByRecursive(child);
}else {
viewCount++;
}
}
}
return viewCount;
}
复制代码
2.非递归方式
public static int getViewCount(View root){
int viewCount = 0;
if (null == root){
return 0;
}
viewCount++;
if (root instanceof ViewGroup){
LinkedList<ViewGroup> queue = new LinkedList<>();
queue.add((ViewGroup) root);
while (!queue.isEmpty()){
ViewGroup parent = queue.removeFirst();
for (int i = 0; i < parent.getChildCount(); i++) {
viewCount++;
View child = parent.getChildAt(i);
if (child instanceof ViewGroup){
queue.add((ViewGroup) child);
}
}
}
}
return viewCount;
}
复制代码
转载于:https://juejin.im/post/5d010ddbe51d45554877a5b4