关于Layout Weight一些使用技巧
LinearLayout中通過layout weight屬性來表示這個孩子視圖view在整個手機屏幕占的大小比例。
一般不在孩子視圖里面寫這個屬性的時候,則默認為0
android:layout_weight="0"For example, if there are three text fields and two of them declare a weight of 1, while the other is given no weight, the third text field without weight will not grow and will only occupy the area required by its content. The other two will expand equally to fill the space remaining after all three fields are measured. If the third field is then given a weight of 2 (instead of 0), then it is now declared more important than both the others, so it gets half the total remaining space, while the first two share the rest equally.
比如,如果一個LinearLayout有3個text的孩子視圖,其中2個聲明layout_weight=1;另外一個沒有聲明,即默認為0,占用的空間大小應該和它的內容一樣。那么這2個聲明了為1的,就平分剩下的空間。
如果第3個聲明不是默認為0而是1的話,那么第3個聲明占用了全部空間的一半,另外2個聲明了1的平分另外的一半.
看下面一個例子:
<?xml?version="1.0"?encoding="utf-8"?> <LinearLayout?xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent"android:paddingLeft="16dp"android:paddingRight="16dp"android:orientation="vertical"?><EditTextandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:hint="@string/to"?/><EditTextandroid:layout_width="fill_parent"android:layout_height="0dp"android:layout_weight="1"android:hint="@string/subject"?/><EditTextandroid:layout_width="fill_parent"android:layout_height="0dp"android:layout_weight="1"android:gravity="top"android:hint="@string/message"?/><Buttonandroid:layout_width="100dp"android:layout_height="wrap_content"android:layout_gravity="top"android:text="@string/send"?/> </LinearLayout>上面運行的結果如下:
明顯to和send所在的區域,因為默認layout_weight不顯示;所以大小默認為0,占用的空間為內容大小。
其他的2個edit平均占用剩下的空間。
關于
?android:layout_height="0dp"android:layout_weight="1"為什么藥這樣設置,可以看文檔上面的這段話:
Equally weighted children
To create a linear layout in which each child uses the same amount of space on the screen, set theandroid:layout_height?of each view to?"0dp"?(for a vertical layout) or theandroid:layout_width?of each view to?"0dp"?(for a horizontal layout). Then set the?android:layout_weight?of each view to?"1".
轉載于:https://my.oschina.net/liangzhenghui/blog/192361
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的关于Layout Weight一些使用技巧的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: B端产品如何寻找竞品?
- 下一篇: 输入一行电报文字,将字母变成其下一字母(