android 遍历所有view,Android 算法:遍历ViewGroup找出所有子View
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;
}
總結
以上是生活随笔為你收集整理的android 遍历所有view,Android 算法:遍历ViewGroup找出所有子View的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: redirect java 配置_Jav
- 下一篇: 电大法学本科计算机考试题,2016年电大