一、weightSum
举个例子来说明weightSum,例如android:weightSum=”5” 表示这个LinearLayout总共平分成5块大小区域;然后再LinearLayout里面的控件,使用android:layout_wetght=“1”,这表示它占用整个布局的1/5。但是要注意要约束的是宽的话要设置android:layout_with=”0dp”。
<?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="wrap_content"
android:orientation="horizontal"
android:weightSum="5"
xmlns:app="http://schemas.android.com/apk/res-auto">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#f0e"
android:layout_weight="1"
android:text="TextView1" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#0fe"
android:layout_weight="3"
android:text="ThisIsTextView2"
/>
</LinearLayout>
将屏幕宽度分为5份,第一个占1份,第二个占3份;就张下面的样子。
二、layout_weight
他的作用是分配LinearLayout额外的空间。
接下来看图说话哈:
先看布局,布局为线型水平排列的两个TextView,布局如下:
<!--注意这里的宽度为match_parent,否则看不到效果-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#f0e"
android:text="TextView1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#0fe"
android:text="ThisIsTextView2"
/>
</LinearLayout>
1、没有分配权重时:
接下来给两个TextView分配权重,第一个的权值为1,第二个为2
2、当android:layout_width=”wrap_content”
首先两个TextView的宽度设为wrap_content,我门之前提过android:layout_weight是分配剩余的空间。所以在两个TextView分配完自己应得的宽度后,把剩余的部分划分为3份(权值的1+2=3),第一个TextView分的1/3,第二个TextView分的2/3,然后就变成这样了。
3、当android:layout_width=”0dp”
当两个TextView的宽度设为0dp后样子就不同了吧,我们设置他的宽度为0,就是相当于省去了分配自己宽度的步骤,就直接将剩余的部分分为3份,第一个TextView分到1/3,第二个分到2/3。
4、当android:layout_width=”match_parent”
是不是看到这有一点点蒙圈呢,一定要记住他的作用是分配剩余的内容。这两个TextVIew的宽度都是填充父窗口,本身的宽度就是match_parent,下面计算一下:
- 1)看看还剩多少空间
match_parent-match_parent-match_parent=-match_parent剩余的空间为-match_parent;
- 2)将剩余的空间分份,每分占多少
-match_parent/(1+2)=-match_parent/3;
第一个TextView应分得的剩余空间:-match_parent/3;
第二个TextView应分得的剩余空间:-2*match_parent/3;
- 3)计算看看每个View真实的宽度
第一个TextView的真实宽度:match_parent+(-match_parent/3)=match_parent*2/3;
第二个TextView的真实宽度:match_parent+(-2*match_parent/3)=match_parent/3;
计算完之后就是上面的样子了,其实上两种情况也是通过这样的计算方式计算得到的。
公式(水平排列的哈):
View的真实宽度=View的初初始宽度+剩余的宽度/所有View权重加和*该View所占权重值
剩余的宽度=父View的宽度-所有View的宽度
自我总结:
weightSum是将整体平均分多少份然后利用权重,给每个View分配应占空间。
layout_weight是分配剩余空间(是剩余的)