public int count1(View root) {
int viewCount = 0;
if (null == root) {
return 0;
}
if (root instanceof ViewGroup) {
viewCount++;
for (int i = 0; i < ((ViewGroup) root).getChildCount(); i++) {
View view = ((ViewGroup) root).getChildAt(i);
if (view instanceof ViewGroup) {
viewCount += count1(view);
} else {
viewCount++;
}
}
}
return viewCount;
}
非递归实现
/**
* 非递归统计一个View的子View数(包含自身)
*
* @param root
* @return
*/
public int count(View root) {
int viewCount = 0;
if (null == root) {
return 0;
}
if (root instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) root;
LinkedList<ViewGroup> queue = new LinkedList<ViewGroup>();
queue.add(viewGroup);
while (!queue.isEmpty()) {
ViewGroup current = queue.removeFirst();
viewCount++;
for (int i = 0; i < current.getChildCount(); i++) {
if (current.getChildAt(i) instanceof ViewGroup) {
queue.addLast((ViewGroup) current.getChildAt(i));
} else {
viewCount++;
}
}
}
} else {
viewCount++;
}
return viewCount;
}
网友评论