Activity实现遍历ViewTree

前言

昨天的金山笔试有一题通过Activity来遍历ViewTree,当场去世,就想着应该有一个View的入口来让我递归,现在才知道怎么做

废话不说,来上代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
private void getAllViews(Activity act) {
// 可以写个函数调用的嘛,当时真的是傻了
List<View> list = getAllChildViews(act.getWindow().getDecorView());
}
private List<View> getAllChildViews(View view) {
List<View> allchildren = new ArrayList<View>();
if (view instanceof ViewGroup) {
// 判断是否此View是否为ViewGroup,也就是layout啦(不准确的说法)
ViewGroup vp = (ViewGroup) view;
Log.d("GroupView",vp.getClass().getName());
for (int i = 0; i < vp.getChildCount(); i++) {
View viewchild = vp.getChildAt(i); // 取得子View
allchildren.add(viewchild);
if(viewchild instanceof ViewGroup){}
else {
Log.d("Child",viewchild.getClass().getName());
}
//再次调用
allchildren.addAll(getAllChildViews(viewchild));
}
}
return allchildren;
}

尾巴

金山的笔试还是比较基础的,Java和Android还有一些基础算法,还是很想去金山的QAQ

分享到: