Is it possible to parameterize an ArrayList from a method parameter? For instance, I have a method getAllViewsFromRoot(View root) which retrieves all Views from a layout. Now I want a method that gets all ProgressBars in a layout, so I can just use this (toolkit)method:
public static ArrayList<ProgressBar> getAllProgressBars(View root) {
ArrayList<View> allviews = getAllViewsFromRoot(root);
ArrayList<ProgressBar> results = new ArrayList<ProgressBar>();
for (View view : allviews)
if (view instanceof ProgressBar)
results.add((ProgressBar)view);
return results;
}
But since I need to do this for different kinds of Views, I wondered if this is possible in a more generic way, passing on the class in the method. I hoped this would work, but it doesn't:
public static ArrayList<?> getViewsFromViewGroup(ViewGroup root, Class clazz) {
ArrayList<View> views = getAllViewsFromRoots(root);
ArrayList<View> result = new ArrayList<clazz>();
for (View view : views) {
if (clazz.isInstance(view.getClass())) {
result.add(view);
}
}
return result;
}
And somewhere else I would call ArrayList<ProgressBar> pbs = Toolkit.getViewsFromViewGroup(root, ProgressBar.class).
In other words, can I specify how I want to strong type the ArrayList with a method parameter?
Is any sort of what I want possible? I don't necessarily need it badly, but I like to solve problems in a generic way.
EDIT
I've managed to get the code working with the answer below (Thanks to thkala). It's actually way easier that I suspected.
public static <T> ArrayList<T> getViewsFromViewGroup(View root, Class<T> clazz) {
ArrayList<T> result = new ArrayList<T>();
for (View view : getAllViewsFromRoots(root))
if (clazz.isInstance(view))
result.add(clazz.cast(view));
return result;
}
So if you want to retrieve all ProgressBars from a certain point in your layout, just call:
ArrayList<ProgressBar> myPbs = Toolkit.getViewFromViewGroup(myRootView, ProgressBar.class);