Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any easy, generic way in Android to get the root View of a layout?

I'm wondering if there is a general-purpose method in the Android Activity class to allow you to get the root View of that Activity's layout. I know I can do it this way:

View v = findViewById(R.id.root_view_id) 

But I would like to be able to do it without having to pass in the ID of the root view. I need to do this for a lot of different Activities, and it would be a lot more convenient if I had a one-size-fits-all method call to accomplish the task.

like image 538
Russell Stewart Avatar asked Mar 30 '11 15:03

Russell Stewart


People also ask

How do I get root view?

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.

What is a root view?

RootView is the View in which all the other views are placed. It is like the root node in a tree structure which is the parent to all the children. For example, you have multiple Buttons in your layout which are placed inside a LinearLayout.


1 Answers

This answer and comments give one method:

findViewById(android.R.id.content) 

Given any view in your hierarchy you can also call:

view.getRootView() 

to obtain the root view of that hierarchy.

The "decor view" can also be obtained via getWindow().getDecorView(). This is the root of the view hierarchy and the point where it attaches to the window, but I'm not sure you want to be messing with it directly.

like image 100
Matthew Willis Avatar answered Oct 16 '22 00:10

Matthew Willis