ArrayList<View> getAllChildren(View v) { if (!(v instanceof ViewGroup)) { ArrayList<View> viewArrayList = new ArrayList<View>(); viewArrayList.add(v); return viewArrayList; } ArrayList<View> result = new ArrayList<View>(); ViewGroup group = (ViewGroup) v; for (int i = 0; i < group.getChildCount(); i++) { View child = group.getChildAt(i); ArrayList<View> viewArrayList = new ArrayList<View>(); viewArrayList.add(v); viewArrayList.addAll(getAllChildren(child)); result.addAll(viewArrayList); } return result; }
第一种是深度优先遍历所有子view,需要递归调用
ArrayList<View> getAllChildren(View v) { ArrayList<View> visited = new ArrayList<View>(); ArrayList<View> unvisited = new ArrayList<View>(); unvisited.add(v); while (!unvisited.isEmpty()) { View child = unvisited.remove(0); visited.add(child); if (!(child instanceof ViewGroup)){ continue; } ViewGroup group = (ViewGroup) child; final int childCount = group.getChildCount(); for (int i=0; i < childCount; i++) { unvisited.add(group.getChildAt(i)); } } return visited; }
第二种方法是宽度优先遍历,只需循环即可
- 本文固定链接: https://freemanapp.com/zh/?p=718
- 转载请注明: freeman 于 FreemanApp 发表