I wrote a function to traverse an Android view and find all children of a given class. Had quite a bit of trouble, but with autocorrect, I finally got it working. The problem is that I don't understand why it works (always scary).
There are 2 things that throw me:
- Why is
@SuppressWarnings("unchecked")
required? - What is the first
<classType>
in the method declaration called and supposed to do?
I'd prefer to understand my code than just blindly go with what works.
@SuppressWarnings("unchecked")
public <classType> ArrayList<classType> findChildrenByClass(Class<?> classType, ViewGroup viewGroup) {
ArrayList<classType> returns = new ArrayList<classType>();
View current_child;
ArrayList<classType> new_children;
if (viewGroup.getChildCount() > 0) {
for (int i=0;i<viewGroup.getChildCount();i++) {
current_child = (View)viewGroup.getChildAt(i);
if (current_child.getClass().equals(classType)) {
returns.add((classType)current_child);
}
if (current_child instanceof ViewGroup
&& ((ViewGroup)current_child).getChildCount() > 0
) {
new_children = findChildrenByClass(classType, (ViewGroup)current_child);
returns.addAll(new_children);
}
}
}
return returns;
}
EDIT: To help others who were confused like me, this is the final revised version
public <T> ArrayList<T> findChildrenByClass(Class<T> classType, ViewGroup viewGroup) {
ArrayList<T> returns = new ArrayList<T>();
View current_child;
ArrayList<T> new_children;
if (viewGroup.getChildCount() > 0) {
for (int i=0;i<viewGroup.getChildCount();i++) {
current_child = (View)viewGroup.getChildAt(i);
if (current_child.getClass().equals(classType)) {
returns.add((T)current_child);
}
if (current_child instanceof ViewGroup
&& ((ViewGroup)current_child).getChildCount() > 0
) {
new_children = findChildrenByClass(classType, (ViewGroup)current_child);
returns.addAll(new_children);
}
}
}
return returns;
}