Android中4种基本布局简单介绍和总结

Android中4种基本布局

线性布局LinearLayout

LinearLayout线性布局,是一种非常常用的布局方式。此布局会将控件在线性方向上依次排列,方向有水平和垂直两种,首先看一下垂直方向上的布局格式,代码如下:

<LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="第一个按钮"/>
        <Button
            android:id="@+id/btn2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="第二个按钮"/>
        <Button
            android:id="@+id/btn3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="第三个按钮"/>
    </LinearLayout>

我们在LinearLayout中添加了三个Button,每个Button的长和宽都是wrap_content,并在android:orientation中指定了排列方向是vertical即垂直方向,运行结果如下图:
这里写图片描述
然后我们修改一下LinearLayout的排列方向:

<LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        ....
    </LinearLayout>

将android:orientation中属性值从vertical改为horizontal,即将排列方向从垂直改为水平方向,运行结果如下:
这里写图片描述
这里要注意一点 如果LinearLayout的排列方向是horizontal,内部的控件就绝对不能将宽度指定为match_parent,因为这样,一个控件就会将水平方向占满,其他的控件就没法放了,vertical亦如此。

相对布局RelativeLayout

这是一个常用的布局,可以通过相对定位的方式让控件出现在布局的任何位置

<RelativeLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="第一个按钮"/>
        <Button
            android:id="@+id/btn2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/btn1"
            android:text="第二个按钮"/>
        <Button
            android:id="@+id/btn3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/btn2"
            android:text="第三个按钮"/>

    </RelativeLayout>

运行结果:
这里写图片描述

帧布局FrameLayout

这个比较简单,没有方便的定位方式,所有的控件都默认摆放在布局的左上角。不是很常用。

百分比布局

这是以前没有的新增布局,为了解决控件平分布局的难题,在这种布局中,不再使用wrap_content和match_parent来指定控件大小,而是直接指定控件在布局中所占百分比,这样就可以轻松实现平分布局甚至任意比例分割布局

此文章只是简单介绍和总结四大基本布局,更详细的讲解可转到Android开发之基本控件和详解四种布局方式查阅

猜你喜欢

转载自blog.csdn.net/source_sc/article/details/80565233
今日推荐