获取activity上所有指定类型的控件

版权声明:【敦格作品】,欢迎引用,注明出处:http://blog.csdn.net/shuaihj https://blog.csdn.net/shuaihj/article/details/46670495

Android获取所有指定类型的子控件,这样就不需要逐个使用findViewByID来获取控件,来达到控制状态的目的了。

/**
  * 获取所有指定类型的子控件
  * @param T
  * @return
  */
 private List<View> getAllChildViews(Class<?> T) {

  View view = this.getWindow().getDecorView();

  return getAllChildViews(view, T);

 }
 private List<View> getAllChildViews(View parent, Class<?> T) {

  List<View> allchildren = new ArrayList<View>();

  if (parent instanceof ViewGroup) {

   ViewGroup vp = (ViewGroup) parent;

   for (int i = 0; i < vp.getChildCount(); i++) {

    View viewchild = vp.getChildAt(i);

    if (viewchild.getClass().equals(T)) {
     allchildren.add(viewchild);
    }

    allchildren.addAll(getAllChildViews(viewchild, T));

   }

  }

  return allchildren;
 }

猜你喜欢

转载自blog.csdn.net/shuaihj/article/details/46670495