相对布局与帧布局有何区别?

9
我刚开始学习android编程,从文档中了解到,RelativeLayout主要用于需要根据某些规则放置视图的情况,而FrameLayout则适用于需要重叠视图的情况。
但是不幸的是,在下面的程序中,我使用RelativeLayout来完成了FrameLayout的工作。虽然我的代码可以工作,但为了更好地理解,我是否忽略了一些区别呢? 此外,按钮是如何出现在我的图片上的?(即使其他图片也重叠了。)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/ic_launcher"
    />

<ImageView
    android:id="@+id/imageView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/ic_launcher"
    android:layout_alignParentTop="true"
    android:layout_alignLeft="@id/imageView1"
    />

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/imageView1"
    android:gravity="center"
    android:orientation="horizontal"
    android:weightSum="1.0" >

<Button
    android:id="@+id/button1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="0.33"
    android:text="Login" />

<Button
    android:id="@+id/button2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="0.33"
    android:text="Register" />

<Button
    android:id="@+id/button3"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="0.33"
    android:text="Try application" />

</LinearLayout>

</RelativeLayout>

https://dev59.com/J2445IYBdhLWcg3wWZAU#4905403 - Nermeen
3个回答

18

RelativeLayout 可以使用:

android:layout_toEndOf="@id/some_view"
android:layout_toStartOf="@id/some_view"
android:layout_above="@id/some_view"
android:layout_below="@id/some_view"

为了确保视图之间正确地对齐,FrameLayout与其类似,只使用重力来显示它的视图(没有关联)。

我还建议你看一下ConstraintLayout组件。ConstraintLayout允许你创建具有扁平化视图层次结构(没有嵌套视图组)的大型和复杂布局。它类似于RelativeLayout,因为所有视图都根据兄弟视图和父布局之间的关系进行布局,但比RelativeLayout更灵活,并且可以更容易地使用Android Studio的布局编辑器。


10

RelativeLayout 是一种基于视图关系的布局管理器。它可以根据某些规则帮助您排列UI元素。您可以指定诸如:将此与父元素的左边缘对齐,将此放置于此元素的左侧/右侧等内容。

FrameLayout 允许在Z轴上进行位置设置。也就是说,您可以将视图元素堆叠在彼此之上。


2
你也可以在RelativeLayout中进行堆叠。 - NikkyD

0

RelativeLayout - 顾名思义,在这个视图组中,视图相对于彼此放置。RelativeLayout 最常用的属性是

android:layout_toLeftOf="@id/some_view1"
android:layout_toRightOf="@id/some_view2"
android:layout_above="@id/some_view3"
android:layout_below="@id/some_view4"
android:layout_toendof="@id/some_view5"
android:layout_tostartof="@id/some_view6"

视图相对于彼此放置。在开发复杂设计时非常有帮助。

FrameLayout - 它表现为单个对象,视图不是相对于彼此放置,而是根据FrameLayout的位置。FrameLayout采用最大子视图的大小。

android:gravity="center_horizontal|center_vertical|bottom"

使用上述属性修改子视图的位置。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接