Enumerate/Iterate all Views in Activity?

后端 未结 8 581
忘了有多久
忘了有多久 2020-12-09 17:33

Is there a way to iterate through all the views in your Activity? Something like:

Iterator it = getViewIterator();
...

Does this exi

8条回答
  •  佛祖请我去吃肉
    2020-12-09 17:52

    If you want to avoid the ugly for (int i = 0; ....) you can use a static wrapper

    public class Tools
    {
        public static Iterable getChildViews(final ViewGroup view)
        {
            return new Iterable()
            {
                int i = -1;
    
                @NonNull
                @Override
                public Iterator iterator()
                {
                    return new Iterator()
                    {
                        int i = -1;
                        @Override
                        public boolean hasNext()
                        {
                            return i < view.getChildCount();
                        }
    
                        @Override
                        public View next()
                        {
                            return view.getChildAt(++i);
                        }
                    };
                }
    
            };
        }
    }
    

    and use it like so

    for (View view :  Tools.getChildViews(viewGroup))
    

    of course this is slightly less efficient since you are creating a new Iteratable object every time you iterate, but you could build on this a more efficient algo if you want.

提交回复
热议问题