In Android, I know how to overlay two images and to animate them. The question is how to overlay the second image at a specific location over the first image.
As an example, the first image is the image of an appliance with a power switch, the second image is the power LED that will glow when animated.
I would like to know how I can specify the location of the power LED in the overlay so that it covers the power switch.
One thing you can do is to put both images inside a
FrameLayout, with the width/height on both set towrap_content. The last one you add to theFrameLayoutwill be on top. Then you can position the two images independently in one of several ways:1) You could set the
layout_gravityof both items totop|left, then setlayout_marginTopandlayout_marginLeftto position the two images relative to the upper left corner of theFrameLayout.2) If you want to, say center image B on top of image A, you could set image A to
layout_gravity top|left,layout_marginLeft0,layout_marginTop0, then setlayout_gravityon image B tocenter. This approach is a bit more robust with respect to running on various devices. You can even use the margins to offset image B with respect to its centered position.You should get the idea at this point. You can combine
layout_gravityalong with margins to position the images as you need.Some caveats:
1) This is not a very efficient way to go about things. If it’s just two images in a larger layout, no big deal. But rendering performance will suffer if you do this technique many times in a layout. If that’s the case, you should consider creating a custom view instead.
2) You need to explicitly set the
layout_gravityon an item contained within aFrameLayout. OtherwiseFrameLayoutwill ignore thelayout_marginTopandlayout_marginLeftattributes on your child views.Finally, you can do this same trick with
RelativeLayout, using its attributes to position the images in relation to one another. LikeFrameLayout, the last view added to the layout shows up on top of the others.