I have a pretty annoying problem here, as Im still trying to internalize each and every bits of what I am doing,
I currently have a LinearLayout, then upon onCreate of the Activity, I will populate or inflate several other LinearLayout’s with Buttons, my problem is that when I try to access the button, it seems that I’m not getting any close or deeper from the LinearLayout, all I can get is the LinearLayout(Parent) and the other LinearLayout(Children), I believe there is a way, Im just totally confused how to do it.
LinearLayout
->LinearLayout(Child1)->Button1, Button2, Button3
->LinearLayout(Child2)->Button4, Button5, Button6
How would I be able to access and get the Buttons?
My source;
for (int x=0; x<ll.getChildCount(); x++){
View v = ll.getChildAt(x);
Class c = v.getClass();
if(c == LinearLayout.class){
for(int y=0; y< ; y++){
**I know there is something that must be done here, likewise, is this the most
efficient way of doing things?
}
}
Log.i("test", c.getName());
}
Only the LinearLayout(Parent) exist in the XML, others are inflated run-time.
You should be able to simply cast
vto aLinearLayout, then access its children just like you did with its parent. Something like:Depending on your exact hierarchy you could possibly simplify this by removing the reflection and simply doing a null check (if needed, wrap it in a try/catch and catch a
ClassCastException). I’ve typically done something like this in situations where I need to traverse a layout tree that’s dynamically generated:This is an untested example (could need better exception handling depending on your requirements and layouts) but hopefully it gives you the general idea. If you want to be a little bit more type-agnostic you could also use a cast to
ViewGroupinstead. That would allow you to potentially use different kinds of layout containers as children, if needed, as they are subclasses ofViewGroup(which is where they inheritgetChildAt()andgetChildCount()from).