Is it possible to place one view over another in android?

kiki picture kiki · Sep 29, 2010 · Viewed 58.1k times · Source

Can we place a small view over another large view? For example, I have a VideoView which is playing a file in the background. Over this, somewhere in the middle/corner, I want to place another ImageView.

But in Linear/Relative Layout, views can be placed only one after another or relative to each other, and AbsoluteLayout is advised against. So what do I do?

Answer

Stephan Henningsen picture Stephan Henningsen · Sep 15, 2016

The FrameLayout is the simplest ViewGroup and stacks the Views in the order they're defined in layout XML (or added programmatically); the first will be lower, and the last will be on top.

Here is an example where two Views are stacked and offset to better illustrate the point:

enter image description here

Here is the actual layout XML with the two overlapping TextView boxes. The offset of the two boxes is done using android:layout_gravity while android:gravity is used for centering the text itself within each box.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="100dp"
    android:layout_height="100dp">

    <TextView
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_gravity="top|left"
        android:background="@android:color/holo_blue_light"
        android:gravity="center"
        android:text="First is below"/>

    <TextView
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_gravity="bottom|right"
        android:background="@android:color/holo_green_light"
        android:gravity="center"
        android:text=" Last is on top"/>

</FrameLayout>