For-Each 循环:将布局转换为视图数组?

For-Each Loop: convert a layout into a View array?

如题所述,

假设 我有一个 layout(如 RelativelayoutLinearLayout 等),其中有很多 Views.


P.S。我知道你可以这样做:

for(int i=0;i<layout.getChildCount();i++){
    View v=layout.getChildAt(i);
    v.doSomething(parameters);
}

为什么不创建一个像这样的辅助方法:

public final class ViewGroupHelper {

    public static void forEach(@NonNull ViewGroup group,
                               @NonNull Action action) {
        for (int i = 0; i < group.getChildCount(); i++) {
            final View view = group.getChildAt(i);
            action.apply(view);
        }
    }

    public interface Action {
        void apply(@NonNull View view);
    }

    private ViewGroupHelper() {}
}

...

ViewGroupHelper.forEach(layout, new ViewGroupHelper.Action() {
    @Override
    public void apply(@NonNull View view) {
        view.doSomething();
    }
});

或使用 lambda ViewGroupHelper.forEach(layout, view -> view.doSomething());