【发布时间】:2017-01-21 07:34:35
【问题描述】:
我有一个扩展 View 类的定制视图。我想要我的自定义视图的 2 个实例直接层叠在一起。我的布局文件应该如何实现这一点?
【问题讨论】:
标签: android
我有一个扩展 View 类的定制视图。我想要我的自定义视图的 2 个实例直接层叠在一起。我的布局文件应该如何实现这一点?
【问题讨论】:
标签: android
原来 FrameLayout 是我想要的。只需在您的布局中执行此操作:
<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>
【讨论】:
使用RelativeLayout。 RelativeLayout 后面的子代将与前面的子代重叠。
【讨论】:
虽然您确实可以使用 RelativeLayout 和 FrameLayout 实现分层,但在 API 21 及更高版本中......情况发生了变化。
在 API 21 及更高版本中,xml 较晚的子代并不意味着它将与较早的子代重叠。相反,它使用Elevation 来确定哪个视图将与其他视图重叠(Z-Index)。
例如,如果你有这样的东西。
<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>
View 将不可见,即使它是在 Button 之后添加的。这是因为Button 的海拔高于View。要重新排列 Z-Index,您可以将 elevation 属性添加到各个视图。
<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>
这样View 将与Button 重叠。
更多信息 高度和阴影:https://material.io/guidelines/material-design/elevation-shadows.html
【讨论】: