What method should I call to know if an Activity has its contentView (once the method setContentView() has been called)?
8 Answers
this.getWindow().getDecorView().findViewById(android.R.id.content)
or
this.findViewById(android.R.id.content)
or
this.findViewById(android.R.id.content).getRootView()
-
5
-
1this works fine as far as fetching the Parent view is concerned... BUt..if i try this.findViewById(android.R.id.content).setBackgroundDrawable(d); it dosent work.. Can you please suggest.. Thanks in advance Aug 2, 2013 at 9:08
-
3If you install a layout from XML using
setContentView(R.layout.my_view)
, this returns the parent of that layout. Aug 26, 2013 at 23:46 -
Hello @ernest I have a sort question like If in my layout i have one image on top than two tab in tab bar. and in bottom a SatelliteMenu, Want to do blur on menu items are opened. May 12, 2015 at 7:30
-
1
You can get the view Back if you put an ID to your Layout.
<RelativeLayout
android:id="@+id/my_relative_layout_id"
And call it from findViewById ...
-
This is the most robust way to get the root of an installed layout. Aug 26, 2013 at 23:47
-
3
-
2@trans View contentView = findViewById(R.id.my_relative_layout_id); Jan 13, 2017 at 3:04
How about
View view = Activity.getCurrentFocus();
-
-
1@aeskreis because in my case it returns null
currentFocus?.let { ... }
– user924Apr 5, 2019 at 12:32
You can also override onContentChanged()
which is among others fired when setContentView()
has been called.
-
ernest's answer will give you the current focussed view even if contains scrollable view– YuDroidSep 8, 2012 at 14:06
If you are using Kotlin
this.findViewById<View>(android.R.id.content)
.rootView
.setBackgroundColor(ContextCompat.getColor(this, R.color.black))
There is no "isContentViewSet" method. You may put some dummy requestWindowFeature call into try/catch block before setContentView like this:
try { requestWindowFeature(Window.FEATURE_CONTEXT_MENU); setContentView(...) } catch (AndroidRuntimeException e) { // do smth or nothing }
If content view was already set, requestWindowFeature will throw an exception.
The best option I found and the less intrusive, is to set a tag param in your xml, like
PHONE XML LAYOUT
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:tag="phone"/>
TABLET XML LAYOUT
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:tag="tablet">
...
</RelativeLayout>
and then call this in your activity class:
View viewPager = findViewById(R.id.pager);
Log.d(getClass().getSimpleName(), String.valueOf(viewPager.getTag()));
Hope it works for u.
-
4