如何分层视图

Fin*_*ner 17 android

我有一个扩展View类的自定义视图.我希望我的自定义视图的2个实例直接在彼此之上分层.我的布局文件应该如何实现这一目标?

Fin*_*ner 29

原来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>
Run Code Online (Sandbox Code Playgroud)

  • 谢了哥们.我对此很疯狂,这看起来效果很好.我以为FrameLayout一次只能容纳1个可见的子视图......我已经在尝试创建自己的布局了,就像在想:必须有一个更简单的方法!PS哦,如果不是很明显,默认情况下会从上到下渲染视图,因此board2会被绘制在board1之上. (2认同)

Com*_*are 24

用一个RelativeLayout.RelativeLayout遗嘱的后期儿童与早期儿童重叠.


ald*_*dok 5

虽然你可以在API 21及更高版本中使用RelativeLayout和实现分层FrameLayout,但事情已经发生了变化.

在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>
Run Code Online (Sandbox Code Playgroud)

该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>
Run Code Online (Sandbox Code Playgroud)

这种方式View会重叠Button.

有关高程和阴影的更多信息:https://material.io/guidelines/material-design/elevation-shadows.html