I want to find all child views for given root view.
public List<View> getAllChildViews(View rootView)
{
//return all child views for given rootView recursively
}
Consumer of this method will pass rootView as follows
//client has some Custom View
List<View> childViews = getAllChildViews(customView.getRootView()); //get root view of custom view
I can type cast rootView to particular layout and then get all children ( at leaf level ) but I am not sure what will be the type of root view. It can be ScrollView or any different layout
Kotlin extension for this solution:
fun View.getAllChildren(): List<View> {
val result = ArrayList<View>()
if (this !is ViewGroup) {
result.add(this)
} else {
for (index in 0 until this.childCount) {
val child = this.getChildAt(index)
result.addAll(child.getAllChildren())
}
}
return result
}
Just call myView.getAllChildren()
on any view
private List<View> getAllChildren(View v) {
if (!(v instanceof ViewGroup)) {
ArrayList<View> viewArrayList = new ArrayList<View>();
viewArrayList.add(v);
return viewArrayList;
}
ArrayList<View> result = new ArrayList<View>();
ViewGroup viewGroup = (ViewGroup) v;
for (int i = 0; i < viewGroup.getChildCount(); i++) {
View child = viewGroup.getChildAt(i);
//Do not add any parents, just add child elements
result.addAll(getAllChildren(child));
}
return result;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With