What is the purpose of FrameLayout and in which scenario should we use it?

2.8k views Asked by At

What purpose does FrameLayout serve in Android? Is there any specific scenario for which it is designed for?

In my Android application, I have a scenario where I have to show two ImageViews, one over the other. This is a .png image file with a 9-patch drawable over this image.

Which ViewGroup should I use for this purpose: RelativeLayout or FrameLayout?

I also want to know the different scenarios that each of the ViewGroups should be used for.

2

There are 2 answers

2
c2dm On BEST ANSWER

Yes, you can use a FrameLayout in your scenario.

0
alkas On

I don't recall how i got to this question but here is my answer that could help anyone:

As you can see here

FrameLayout is designed to block out an area on the screen to display a single item. Generally, FrameLayout should be used to hold a single child view, because it can be difficult to organize child views in a way that's scalable to different screen sizes without the children overlapping each other.

In general is not useful to have 2 views one over the other because you're going to have overdraw effect (an area of the screen that is getting drawn by the gpu more than once which is really useless).

If you really have to, then you need to use the onDraw method (you can see an example here) and Canvas API (have a look here) and the clipRect method (you can see an example here)

Regarding FrameLayout or RelativeLayout, if you want to keep things simple or your activity has already enough nested layouts, better use FrameLayout. In 2017, there is the constraint layout which could be of some help as well.