枚举/迭代活动中的所有视图?

swi*_*ter 16 android iterator

有没有办法迭代您的Activity中的所有视图?就像是:

__CODE__或者其他的__CODE__扩展__CODE__,你可以使用的功能__CODE____CODE__和遍历所有的
包含意见.

希望这可以帮助.

Har*_*Joy 17

If you have all your Views in a LinearLayout or an other container that extends ViewGroup you can use the functions getChildCount() and getChildAt(int) and iterate through all of the
contained views.

Hope this helps.


Jam*_*mol 9

假设"您的活动中的所有视图"是指层次结构中的每个视图Iterator,Android中没有这样或任何内容允许您迭代所有视图.

ViewGroups getChildCountgetChildAt方法,但他们是关于直接的孩子ViewGroup.因此,您需要访问每个孩子,并检查它是否属于ViewGroup自己,等等.长话短说,我想要这样的功能来查找匹配特定标签的所有视图(findViewWithTag只返回第一个).这是一个可以迭代所有视图的类:

public class LayoutTraverser {

    private final Processor processor;


    public interface Processor {
        void process(View view);
    }

    private LayoutTraverser(Processor processor) {
        this.processor = processor;
    }

    public static LayoutTraverser build(Processor processor) {
        return new LayoutTraverser(processor);
    }

    public View traverse(ViewGroup root) {
        final int childCount = root.getChildCount();

        for (int i = 0; i < childCount; ++i) {
            final View child = root.getChildAt(i);

            if (child instanceof ViewGroup) {
                traverse((ViewGroup) child);
            }
        }
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

像这样使用它:

LayoutTraverser.build(new LayoutTraverser.Processor() {
  @Override
  public void process(View view) {
    // do stuff with the view
  }
}).traverse(viewGroup);
Run Code Online (Sandbox Code Playgroud)