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