It may sound foolish, but I actually can't find anything on it. Is it ok to add multiple views to the root view of activity in Android?
So for example I could go like this:
setContentView(R.layout.main);
setContentView(gLView);
setContentView(otherView);
Or simply retrieve it as a view
FrameLayout layout = (FrameLayout)this.getWindow().getDecorView().findViewById(android.R.id.content);
layout.addView(view1);
layout.addView(view2);
layout.addView(view3);
layout.addView(view4);
It all seems to work on devices I test, but is it guaranteed to work on all of them?
Or should I artificially create single FrameLayout
to add to root view and add everything to this FrameLayout
?
More experiments:
1) if I don't use setContentView
and print:
Log.d("Test", this.getWindow().getDecorView().findViewById(android.R.id.content).getClass().getName());
I get: android.widget.FrameLayout
2) If I set content view to for example GLSurfaceView
and print the same Log.d
It also prints android.widget.FrameLayout
3) And if I dont' use setContentView
at all, and simply do
FrameLayout layout = (FrameLayout)this.getWindow().getDecorView().findViewById(android.R.id.content);
layout.addView(myView);
It attaches the view
So I assume that android.R.id.content
returns not what you set by setContentView
but the parent of what you set, or the actual root view in activity (which turns out is FrameLayout?)
And I am able to add multiple children to it this way, but question is: Am I allowed to do that?
Yes, it's perfectly fine to add multiple content View
s at the root level. The content View
s are simply added to a FrameLayout
container, and it is best practice to simply use it for your layout if a FrameLayout
is all you require for it, instead of adding an additional container layer.
If you are adding a new content View
, then you should use the addContentView()
method instead of setContentView()
, which would cause the existing content to be replaced instead.
Also, it is possible to add multiple View
s to the content container in XML layouts as well by using the <merge>
tag, which would just replace the base FrameLayout
.
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