一、weight(权重)属性详解
1、最简单用法:
实现代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/LinearLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <LinearLayout android:layout_width="0dp" android:layout_height="fill_parent" android:background="#ADFF2F" android:layout_weight="1"/> <LinearLayout android:layout_width="0dp" android:layout_height="fill_parent" android:background="#DA70D6" android:layout_weight="2"/> </LinearLayout>
要实现第一个的1:1的效果,只需要分别把两个LinearLayout的weight改成1和1就可以了 用法归纳: 按比例划分水平方向:将涉及到的View的android:width属性设置为0dp,然后设置为android weight属性设置比例即可;类推,竖直方向,只需设android:height为0dp,然后设weight属性即可! 大家可以自己写个竖直方向的等比例划分的体验下简单用法!
②weight属性详解:
当然,如果我们不适用上述那种设置为0dp的方式,直接用wrap_content和match_parent的话, 则要接着解析weight属性了,分为两种情况,wrap_content与match_parent!另外还要看 LinearLayout的orientation是水平还是竖直,这个决定哪个方向等比例划分
1)wrap_content比较简单,直接就按比例的了
实现代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/LinearLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <TextView android:layout_weight="1" android:layout_width="wrap_content" android:layout_height="fill_parent" android:text="one" android:background="#98FB98" /> <TextView android:layout_weight="2" android:layout_width="wrap_content" android:layout_height="fill_parent" android:text="two" android:background="#FFFF00" /> <TextView android:layout_weight="3" android:layout_width="wrap_content" android:layout_height="fill_parent" android:text="three" android:background="#FF00FF" /> </LinearLayout>
2)match_parent(fill_parent):这个则需要计算了
我们写这段简单的代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/LinearLayout1" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:layout_weight="1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="one" android:background="#98FB98" /> <TextView android:layout_weight="2" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="two" android:background="#FFFF00" /> <TextView android:layout_weight="3" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="three" android:background="#FF00FF" /> </LinearLayout>
计算方法:
假如weight为 1:1:1 则 结果比例为1-2*(1/(1+1+1):1-2*(1/(1+1+1):1-2*(1/(1+1+1)
假如weight为:1:2:3 则结果比例为:1-2*(1/(1+2+3):1-2*(2/(1+2+3):1-2*(3/(1+2+3)