Android | Get all children elements of a ViewGroup

后端 未结 7 1627
星月不相逢
星月不相逢 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:07

    I've reimplemented this method in a recursive way. Not sure it's faster than MH's, but at least it has no duplicates.

    private List getAllViews(View v) {
        if (!(v instanceof ViewGroup) || ((ViewGroup) v).getChildCount() == 0) // It's a leaf
            { List r = new ArrayList(); r.add(v); return r; }
        else {
            List list = new ArrayList(); list.add(v); // If it's an internal node add itself
            int children = ((ViewGroup) v).getChildCount();
            for (int i=0;i

    MH's answer includes the parent view which is being given to the method, so I created this auxiliary method (which is the one to be called).

    I mean, if you call this method on a TextView (which has no children), it returns 0 instead of 1.

    private List getAllChildren(View v) {
        List list = getAllViews(v);
        list.remove(v);
        return list;
    }
    

    TLDR: to count all children copy and paste both methods, call getAllChildren()

提交回复
热议问题