Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through all subviews of an Android view?

I’m working on a game for Android. To help implement it, my idea is to create a subclass of a view. I would then insert several instances of this class as children of the main view. Each instance would handle detecting when it was pressed (via OnTouchListener).

The problem I’m having now is how do I loop through all these sub-views so I can read their statuses and process them? (I.e. when they all reach a certain state something should happen).

Or is there a better way to have several objects on the screen that respond to touch and whose status I can check?

like image 459
Slapout Avatar asked Apr 08 '10 02:04

Slapout


1 Answers

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.

like image 181
Tobrun Avatar answered Sep 20 '22 12:09

Tobrun