Layout_weight是Android开发中一个比较常用的布局属性,在面试中也经常被问到.下面通过实例彻底搞懂Layout_weight的用法.

  先看下面的布局代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="horizontal"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <TextView
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:layout_weight="1"
        android:background="#44ff0000"
        android:gravity="center"
        android:text="111111111111"/>
    <TextView
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:layout_weight="2"
        android:background="#4400ff00"
        android:gravity="center"
        android:text="2"/>
    <TextView
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:layout_weight="3"
        android:background="#440000ff"
        android:gravity="center"
        android:text="3"/>
</LinearLayout>

   在水平方向的线性布局中,有三个TextView,layout_width都是0dp,layout_weight分别为1,2,3,所以这三个TextView应该按1:2:3的比例分布,

   显示效果:

  Android常用布局属性解析 -- Layout_weight

  可以看到,虽然三个TextView是按1:2:3的比例进行分布的,但是第一个TextView却没有和另外两个对齐,这是为什么呢?

  仔细看就能发现,虽然三个TextView不是对齐的,但是第一行的文本是对齐的.

  Android常用布局属性解析 -- Layout_weight

  我们只需将LinearLayout的baselineAligned属性设置为false即可,baselineAligned表示是否以文本基准线对齐.

  Android常用布局属性解析 -- Layout_weight

  这只是对layout_weight属性最基本的用法.假如把第一个TextView的layout_width该为wrap_content,会出现什么情况呢?

  

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="horizontal"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:baselineAligned="false">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="48dp"
        android:layout_weight="1"
        android:background="#44ff0000"
        android:gravity="center"
        android:text="111111111111"/>
    <TextView
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:layout_weight="2"
        android:background="#4400ff00"
        android:gravity="center"
        android:text="2"/>
    <TextView
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:layout_weight="3"
        android:background="#440000ff"
        android:gravity="center"
        android:text="3"/>
</LinearLayout>
View Code

相关文章: