@zzudhj
2015-07-17T02:25:07.000000Z
字数 2510
阅读 1692
Android 属性 布局
在Android开发过程中,在编写布局文件经常会用layout_weight属性:从字面意思上看权重、比值、按比例。。。
通过例子来看看layout_weight的用法
example1:
该布局有三部分组成,title、edit、bottom,其中,为了满足edit可以填充父窗口,可以为EditText添加layou_weight属性。通过Dump view UI hierarchy for Automatorfen 分析,得到结构如图:
通过代码实现
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><TextViewandroid:layout_width="match_parent"android:layout_height="48dp"android:gravity="center"android:text="标题1" /><EditTextandroid:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1" /><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"><Buttonandroid:layout_width="0dp"android:layout_height="48dp"android:layout_weight="1"android:text="save" /><Buttonandroid:layout_width="0dp"android:layout_height="48dp"android:layout_weight="1"android:text="cancel" /></LinearLayout></LinearLayout>
有了初步的认识,就来看看经常会遇到情景
example2:
<TextViewandroid:layout_width="0dp"android:layout_height="match_parent"android:text="textview1"android:background="#ee0000"android:layout_weight="1"/><TextViewandroid:layout_width="0dp"android:layout_height="match_parent"android:text="textview2"android:background="#eeee00"android:layout_weight="2"/><TextViewandroid:layout_width="0dp"android:layout_height="match_parent"android:text="textview3"android:background="#ee0ee0"android:layout_weight="2"/>
example3:
<TextViewandroid:layout_width="match_parent"android:layout_height="match_parent"android:text="textview1"android:background="#ee0000"android:layout_weight="1"/><TextViewandroid:layout_width="match_parent"android:layout_height="match_parent"android:text="textview2"android:background="#eeee00"android:layout_weight="2"/><TextViewandroid:layout_width="match_parent"android:layout_height="match_parent"android:text="textview3"android:background="#ee0ee0"android:layout_weight="2"/>
其中,example2与example3区别
<TextViewandroid:layout_width="xxx".../>
分析可以知道layout_weight表示:控件长度= 原来长度(Length) + 屏幕剩余(SLength)* weight_i,其中屏幕长度为L
example2中:
Length = 0,
SLength= L,
textview1.weight = 1/5
textview1.length = 1/5L;
同理 textview2.length = 2/5L
textview3.length = 2/5L
example3中:
Length= L,
SLength = -2L,
textview1.length = L + (- 2/5 L) = 3/5L
textview2.length = L + (- 4/5 L) = 1/5L
textview3.length = L + (- 4/5 L) = 1/5L
ps:
textview1.weight =1
textview2.weight =2
textview3.weight =3
如果这样设置layout_weight的值,当 android:layout_width="match_parent"的情景下,
你会发现
textview1.length = L + (- 2/6 L) = 2/3L
textview2.length = L + (- 4/6 L) = 1/3L
textview3 不见啦啦啦