Is there a dynamic way to get at the root layout (the one that is the parent to all the other Layouts) in the XML currently set to my Activity?
What I'm after is rather than giving my root layout an explicit id and finding it via findViewById, I'm hoping to get something along the lines of
pseudo code:
this.findTopLayout();
having already called setContentView(R.layout.foo);
I'm not seeing anything in the spec that would do the trick, am I just missing it, or is there no way to do this?
anyview. getRootView(); will be the easiest way. Show activity on this post. in any onClick we will be getting "View view", by using 'view' get the rootView.
In this Android kotlin example we will learn how to get the root view of the current activity. We know that ViewGroup is the base class for other view and view containers, so by using the ViewGroup we will find the current root view of the activity. This ViewGroup will have the fixed Id for the every activity.
SetContentView is used to fill the window with the UI provided from layout file incase of setContentView(R. layout. somae_file). Here layoutfile is inflated to view and added to the Activity context(Window).
The Android SDK provided a method: findViewById() . Functionality-wise, this method performs a singular task — it will give you the reference to the view in XML layouts by searching its ID. And if nothing is found, it will give you the good old NULL , which is said to be the 1-billion dollar mistake by its creator.
You try out this way to get the root layout:
getWindow().getDecorView().findViewById(android.R.id.content);
OR
getWindow().getDecorView().getRootView();
Note that apart from the method described by Grishu, you can also use the method getParent on any view (this includes buttons, imageviews, layouts, etc) to get the parent of that view (the parent returned might also have a parent). Hence, an alternative method would be to loop on getParent from a particular view until getParent returns null. At that point, you would have found the root view of your content view.
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