Loop through all subviews of an Android view?
Android loop through all views
The alternative
public static void recursivelyFindChildren(View view) {
if (view instanceof ViewGroup) {
//ViewGroup
ViewGroup viewGroup = (ViewGroup)view;
for (int i = 0; i < viewGroup.getChildCount(); i++) {
recursivelyFindChildren(viewGroup.getChildAt(i));
}
} else {
//View
}
}
Or you can return something you can use the next approach
@Nullable
private static WebView recursivelyFindWebView(View view) {
if (view instanceof ViewGroup) {
//ViewGroup
ViewGroup viewGroup = (ViewGroup)view;
if (!(viewGroup instanceof WebView)) {
for (int i = 0; i < viewGroup.getChildCount(); i++) {
WebView result = recursivelyFindWebView(viewGroup.getChildAt(i));
if (result != null) {
return result;
}
}
} else {
//WebView
WebView webView = (WebView)viewGroup;
return webView;
}
}
return null;
}
I have made a small example of a recursive function:
public void recursiveLoopChildren(ViewGroup parent) {
for (int i = 0; i < parent.getChildCount(); i++) {
final View child = parent.getChildAt(i);
if (child instanceof ViewGroup) {
recursiveLoopChildren((ViewGroup) child);
// DO SOMETHING WITH VIEWGROUP, AFTER CHILDREN HAS BEEN LOOPED
} else {
if (child != null) {
// DO SOMETHING WITH VIEW
}
}
}
}
The function will start looping over al view elements inside a ViewGroup
(from first to last item), if a child is a ViewGroup
then restart the function with that child to retrieve all nested views inside that child.
@jqpubliq Is right but if you really want to go through all Views you can simply use the getChildCount()
and getChildAt()
methods from ViewGroup
. A simple recursive method will do the rest.