Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to add multiple views to root view of an Activity?

Tags:

android

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?

like image 669
Artūrs Sosins Avatar asked Oct 02 '22 19:10

Artūrs Sosins


1 Answers

Yes, it's perfectly fine to add multiple content Views at the root level. The content Views 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 Views to the content container in XML layouts as well by using the <merge> tag, which would just replace the base FrameLayout.

like image 145
corsair992 Avatar answered Oct 05 '22 12:10

corsair992