Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get root view from current activity

I know how to get the root view with View.getRootView(). I am also able to get the view from a button's onClick event where the argument is a View. But how can I get the view in an activity?

like image 336
Lalith Avatar asked Dec 20 '10 00:12

Lalith


People also ask

How do I get root view from activity?

In activity, normally you tell which resource it should render using setContentView() and the view that you supplied is already the root. If you need the handle of that view, simply put an ID to it in XAML and findViewById() would be fine.

What is a root view in Android?

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.

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.

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


2 Answers

If you need root view of your activity (so you can add your contents there) use

findViewById(android.R.id.content).getRootView() 

Also it was reported that on some devices you have to use

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

instead.

Please note that as Booger reported, this may be behind navigation bar (with back button etc.) on some devices (but it seems on most devices it is not).

If you need to get view that you added to your activity using setContentView() method then as pottedmeat wrote you can use

final ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this             .findViewById(android.R.id.content)).getChildAt(0); 

But better just set id to this view in your xml layout and use this id instead.

like image 149
Dmitry Ryadnenko Avatar answered Sep 26 '22 23:09

Dmitry Ryadnenko


This is what I use to get the root view as found in the XML file assigned with setContentView:

final ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this             .findViewById(android.R.id.content)).getChildAt(0); 
like image 44
pottedmeat Avatar answered Sep 26 '22 23:09

pottedmeat