I'm just going to provide this answer as an alternative @IHeartAndroid's recursive algorithm for discovering all child View
s in a view hierarchy. Note that at the time of this writing, the recursive solution is flawed in that it will contains duplicates in its result.
For those who have trouble wrapping their head around recursion, here's a non-recursive alternative. You get bonus points for realizing this is also a breadth-first search alternative to the depth-first approach of the recursive solution.
private List<View> getAllChildrenBFS(View v) {
List<View> visited = new ArrayList<View>();
List<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;
}
A couple of quick tests (nothing formal) suggest this alternative is also faster, although that has most likely to do with the number of new ArrayList
instances the other answer creates. Also, results may vary based on how vertical/horizontal the view hierarchy is.
Cross-posted from: Android | Get all children elements of a ViewGroup