I have a custom-made view that extends the View class. I would like 2 instances of my custom view layered directly on top of each other. How should my layout file look to ac
Turns out FrameLayout was what I wanted. Just do this in your layout:
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<com.proj.MyView
android:id="@+id/board1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<com.proj.MyView
android:id="@+id/board2"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</FrameLayout>
While it's true that you can achieve layering using RelativeLayout
and FrameLayout
, in API 21 and higher.. things have changed.
In API 21 and higher, the later children of xml doesn't mean it will overlap earlier children. Instead, it uses Elevation
to determine which view will overlap other view (Z-Index).
For example, if you have something like this.
<FrameLayout
android:layout_height="match_parent"
android:layout_width="match_parent">
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
android:text="Hello World"
android:layout_gravity="top" />
<View
android:layout_width="match_parent"
android:layout_height="10dp"
android:background="@android:color/black"
android:layout_gravity="bottom" />
</FrameLayout>
The View
will not be visible even though it was added after Button
. That's because Button
has higher elevation than View
. To rearrange Z-Index you can add elevation
attribute to respective views.
<FrameLayout
android:layout_height="match_parent"
android:layout_width="match_parent">
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
android:text="Hello World"
android:layout_gravity="top"
android:elevation="0dp" />
<View
android:layout_width="match_parent"
android:layout_height="10dp"
android:background="@android:color/black"
android:layout_gravity="bottom"
android:elevation="2dp" />
</FrameLayout>
This way the View
will overlap the Button
.
More Information on Elevation & Shadows: https://material.io/guidelines/material-design/elevation-shadows.html
Use a RelativeLayout
. Later children of the RelativeLayout
will overlap earlier children.