Loop through all subviews of an Android view?
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.
Try this. Takes all views inside a parent layout & returns an array list of views.
public List<View> getAllViews(ViewGroup layout){ List<View> views = new ArrayList<>(); for(int i =0; i< layout.getChildCount(); i++){ views.add(layout.getChildAt(i)); } return views; }