utility to iterate a viewgroup recursively and return a list of child views - Android User Interface

Android examples for User Interface:ListView

Description

utility to iterate a viewgroup recursively and return a list of child views

Demo Code

/*// w ww  .  jav a2s .c om
 * Copyright (C) 2014 VanirAOSP && the Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import java.util.ArrayList;

import android.view.View;
import android.view.ViewGroup;

public class Main {
  /**
   * utility to iterate a viewgroup recursively and return a list of child views
   */
  public static 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 vg = (ViewGroup) v;
    for (int i = 0; i < vg.getChildCount(); i++) {
      View child = vg.getChildAt(i);
      ArrayList<View> viewArrayList = new ArrayList<View>();
      viewArrayList.add(v);
      viewArrayList.addAll(getAllChildren(child));
      result.addAll(viewArrayList);
    }
    return result;
  }

  /**
   * utility to iterate a viewgroup and return a list of child views of type
   */
  public static <T extends View> ArrayList<T> getAllChildren(View root, Class<T> returnType) {
    if (!(root instanceof ViewGroup)) {
      ArrayList<T> viewArrayList = new ArrayList<T>();
      try {
        viewArrayList.add(returnType.cast(root));
      } catch (Exception e) {
        // handle all exceptions the same and silently fail
      }
      return viewArrayList;
    }

    ArrayList<T> result = new ArrayList<T>();
    ViewGroup vg = (ViewGroup) root;
    for (int i = 0; i < vg.getChildCount(); i++) {
      View child = vg.getChildAt(i);
      ArrayList<T> viewArrayList = new ArrayList<T>();
      try {
        viewArrayList.add(returnType.cast(root));
      } catch (Exception e) {
        // handle all exceptions the same and silently fail
      }
      viewArrayList.addAll(getAllChildren(child, returnType));
      result.addAll(viewArrayList);
    }
    return result;
  }
}

Related Tutorials