2010-04-13 29 views
16

我有一个扩展视图类定制的视图。我想我的自定义视图的两个实例直接层叠在一起。我的布局文件应该如何实现这个目标?如何层视图

回答

27

原来的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> 
+2

感谢队友:上 海拔&阴影

更多信息。我对此很感兴趣,而且这似乎工作得很好。我认为FrameLayout一次只能容纳1个可见的子视图......我已经在尝试创建自己的布局,并且像以下这样思考:必须有一个更简单的方法! P.S. 哦,如果不是很明显,观点默认情况下,从顶部呈现为底部,所以board2大干快上的委员会1顶部排出。 – Timo 2011-07-08 07:20:50

+1

非常好。我不得不说,我不喜欢相对布局的使用频率,并且很高兴这个不使用相关布局。 (亲戚们很混乱!每一个对象都需要有一些属性来描述它的位置!这看起来会破坏使用布局的目的......) – ArtOfWarfare 2012-12-07 21:41:36

24

使用RelativeLayoutRelativeLayout的后期子女将重叠较早的子女。

5

虽然这是真的,你可以实现使用RelativeLayoutFrameLayout,在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将重叠Buttonhttps://material.io/guidelines/material-design/elevation-shadows.html