Issue
Suppposed that I have a layout
(like a Relativelayout
, LinearLayout
, etc.) with a ton lot of Views
.
The case here is that I want to do the very same thing to all of them using a
for-each
method.The problem is, you can only
iterate
using thefor-each
method when it qualifies as anarray
.
P.S. I know that you can do it like this:
for(int i=0;i<layout.getChildCount();i++){
final View v=layout.getChildAt(i);
v.doSomething(parameters);
}
- I just have to know if there's another way using the
for-each
method so that I can save time rather than typing that again and again on every app that I develop.
Solution
Why not create a helper method like:
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();
}
});
or with lambda ViewGroupHelper.forEach(layout, view -> view.doSomething());
Answered By - Akaki Kapanadze
Answer Checked By - Katrina (JavaFixing Volunteer)