Android | Get all children elements of a ViewGroup

后端 未结 7 1596
星月不相逢
星月不相逢 2020-12-08 02:56

getChildAt(i) on gets only the direct children of a ViewGroup, is it possible to access to all children without doing nested loops?

7条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-08 03:18

    Here is my (recursive) solution that prints the hierarcy like this:

    android.widget.LinearLayout children:2  id:-1
      android.view.View  id:2131624246
      android.widget.RelativeLayout children:2  id:2131624247
        android.support.v7.widget.AppCompatTextView  id:2131624248
        android.support.v7.widget.SwitchCompat  id:2131624249
    
    
     public static String getViewHierarcy(ViewGroup v) {
            StringBuffer buf = new StringBuffer();
            printViews(v, buf, 0);
            return buf.toString();
        }
    
        private static String printViews(ViewGroup v, StringBuffer buf, int level) {
            final int childCount = v.getChildCount();
            v.getId();
    
            indent(buf, level);
            buf.append(v.getClass().getName());
            buf.append(" children:");
            buf.append(childCount);
            buf.append("  id:"+v.getId());
            buf.append("\n");
    
            for (int i = 0; i < childCount; i++) {
                View child = v.getChildAt(i);
                if ((child instanceof ViewGroup)) {
                    printViews((ViewGroup) child, buf, level+1);
                } else {
                    indent(buf, level+1);
                    buf.append(child.getClass().getName());
                    buf.append("  id:"+child.getId());
                    buf.append("\n");
                }
            }
            return buf.toString();
        }
    
        private static void indent(StringBuffer buf, int level) {
            for (int i = 0; i < level; i++) {
                buf.append("  ");
            }
        }
    

提交回复
热议问题