Android LinearLayout详解

LinearLayout

LinearLayout是所有的子控件在一个方向,垂直或水平的父组件。你可以指定使用android:orientation设置布局的方向。

水平布局:android:orientation=“vertical”

LinearLayout所有的子控件一个接一个,所以一个垂直列表的话,每行只有一个孩子,无论他们有多宽,一个水平列表只会有一行高(最高的孩子的身高,加上填充)。LinearLayout关心每个子控件与其他设置了gravity(右、中心或左对齐)属性之间之间的margin值。

Layout Weight

LinearLayout还支持使用android:layout_weight属性分配个个个体(子控件)的比重。这个属性分配一个“重要”的值对于一个控件在屏幕上应该占多少空间。在父视图中更大的比重值使其扩大剩余的可用于填补的空间。子视图可以指定一个权重值,然后剩余的空间将按照声明的比例被分配给子控件。默认的weight值为零。

例如,如果有三个文本字段和他们两个声明1的比重,而另一个没有比重,没有比重的第三个文本字段是不会向外扩展,只会占据其内容所需的区域。其他两个将扩大同样填补剩下的空间毕竟测量三个字段。如果第三个控件是给定一个比重为2(而不是0),然后现在声明比其他的更重要,所以它将占有一半的总剩余空间,而前两个分享剩余的空间。

Example

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:orientation="vertical" >
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/to" />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/subject" />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="top"
        android:hint="@string/message" />
    <Button
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:text="@string/send" />
</LinearLayout>

上面代码的效果图

Tips:同样比重的子控件

创建一个线性布局,每个孩子在屏幕上使用相同数量的空间,设置android:layout_height每个视图的“0dp”(垂直布局)或android:layout_width每个视图的“0dp”(水平布局)。然后将android:layout_weight每个视图的“1”。

——–意思就是在使用android:layout_weight属性时,请把android:layout_height或者android:layout_width设置为0dp

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值