1.用递归的方式实现
// 遍历viewGroup
public int traverseViewGroup(View view) {
int viewCount = 0;
if (null == view) {
return 0;
}
if (view instanceof ViewGroup) {
//遍历ViewGroup,是子view加1,是ViewGroup递归调用
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
View child = ((ViewGroup) view).getChildAt(i);
if (child instanceof ViewGroup) {
viewCount += traverseViewGroup(((ViewGroup) view).getChildAt(i));
} else {
viewCount++;
}
}
} else {
viewCount++;
}
return viewCount;
}
2.用非递归方式实现
// 遍历viewGroup
public int traverseViewGroup(View view) {
int viewCount = 0;
if (null == view) {
return 0;
}
if (view instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) view;
LinkedListlinkedList = new LinkedList<>();
linkedList.add(viewGroup);
while (!linkedList.isEmpty()) {
//removeFirst()删除第一个元素,并返回该元素
ViewGroup current = linkedList.removeFirst();
viewCount++;
//遍历linkedList中第一个viewGroup中的子view
for (int i = 0; i < current.getChildCount(); i++) {
if (current.getChildAt(i) instanceof ViewGroup) {
linkedList.addLast((ViewGroup) current.getChildAt(i));
} else {
viewCount++;
}
}
}
} else {
viewCount++;
}
return viewCount;
}