Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find root layout in activity [duplicate]

Tags:

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?

like image 774
Yevgeny Simkin Avatar asked Jan 12 '13 03:01

Yevgeny Simkin


People also ask

How do I get root view of activity?

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.

How do I get root view of activity in Kotlin?

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.

What is SetContentView?

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).

How do I find view by ID?

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.


2 Answers

You try out this way to get the root layout:

getWindow().getDecorView().findViewById(android.R.id.content);

OR

getWindow().getDecorView().getRootView();

like image 95
GrIsHu Avatar answered Oct 28 '22 03:10

GrIsHu


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.

like image 31
Dhruv Gairola Avatar answered Oct 28 '22 05:10

Dhruv Gairola