線性布局是程序中最常見的布局方式之一,
線性布局可以分為水平線性布局和垂直線性布局兩種,分別是通過android:orientation="horizontal"和android:orientation="vertical"來控制的
線性布局中,有 幾個及其重要的參數,直接決定元素的布局和位置,這幾個參數是
android:layout_gravity ( 是本元素相對於父元素的對齊方式 )
android:gravity="bottom|right"(是本元素所有子元素的對齊方式,設置在父元素上,多個值用|隔開)
android:layout_gravity (子元素在父元素的對齊方式,設置在子元素上)
當 android:orientation="vertical" 時, 只有水平方向的設置才起作用,垂直方向的設置不起作用。即:left,right,center_horizontal 是生效的。
當 android:orientation="horizontal" 時, 只有垂直方向的設置才起作用,水平方向的設置不起作用。即:top,bottom,center_vertical 是生效的。
android:padding="10dp" (是本元素所有子元素的與父元素邊緣的距離,設置在父元素上)
android:layout_marginLeft="10dp"(子元素與父元素邊緣的距離,設置在子元素上)
android:orientation (線性布局以列或行來顯示內部子元素)
android:layout_weight ="1" 分配分配權重值
下面舉例說明

布局代碼:
<?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:orientation="vertical" > <!-- 垂直布局 --> <LinearLayout android:layout_width="match_parent" android:layout_weight="1" android:orientation="vertical" > <TextView android:layout_height="match_parent" android:layout_width="match_parent" android:layout_weight="1" android:background="#ff0000" /> <TextView android:layout_height="match_parent" android:layout_width="match_parent" android:layout_weight="1" android:background="#00ff00" /> <TextView android:layout_height="match_parent" android:layout_width="match_parent" android:layout_weight="1" android:background="#0000ff" /> </LinearLayout> <!-- 水平布局 --> <LinearLayout android:layout_width="match_parent" android:orientation="horizontal" android:layout_weight="2" > <TextView android:layout_height="match_parent" android:layout_width="match_parent" android:layout_weight="1" android:background="#ff0000" /> <TextView android:layout_height="match_parent" android:layout_width="match_parent" android:layout_weight="1" android:background="#00ff00" /> <TextView android:layout_height="match_parent" android:layout_width="match_parent" android:layout_weight="1" android:background="#0000ff" /> <TextView android:layout_height="match_parent" android:layout_width="match_parent" android:layout_weight="1" android:background="#c0c0c0" /> </LinearLayout> </LinearLayout>
權重:
android:layout_weight="1"通過設置控件的layout_weight屬性以控制各個控件在布局中的相對大小,線性布局會根據該控件layout_weight值與其所處布局中所有控件layout_weight值之和的比值為該控件分配占用的區域。在水平布局的LinearLayout中有4個TxtView,這4個TextView的layout_weight屬性值都為1,那么這4個TextView的大小將拉伸到總大小的四分之一。如果layout_weight指為0,控件會按原大小顯示,不會被拉伸;對於其余layout_weight屬性值大於0的控件,系統將會減去layout_weight屬性值為0的控件的寬度或者高度,再用剩余的寬度或高度按相應的比例來分配每一個控件顯示的寬度或高度。
權重最基本的用法就是 對線性布局指定方向(水平或垂直)上剩余空間分配的一個規則,先把規定的大小占完,再來按比例分配剩余空間
特殊情況:
首先計算數值,所有控件加起來后可能超過屏幕大小了,這個時候剩余值就應該是負的,此時按權重分配,權重大的分得值比較大,但是負的,這個時候加上原來的值,反而變小
權重有一個很有用的特點,在一些特殊應用場景,比如有兩個控件,一個設置了權重,一個不設置權重,那么這個設置權重的控件會后加載渲染。
