2010-04-13 30 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