layout_weight是LinearLayout布局中的一个常用的属性,一般使用该属性的意愿是按照比重分配空间的长度或者宽度,但是若不对该属性原理进行了解,呈现效果却是和理想的大相径庭。
首先解释一下,layout_weight并不是一个完全用来设置大小的属性,某种意义上它是一个对于layout_width或者layout_height属性的补充,优先级低于layout_width属性和layout_height属性。layout_weight分配的事剩余空间的权重。何为剩余空间?剩余空间就是根据各个空间的layout_width属性或者layout_height属性分配完之后剩余的行或者列的值。
结合具体代码分析:
<?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:layout_centerVertical="true"
android:minHeight="@dimen/listitem_min_height">
<TextView
android:layout_width="10dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="test" />
<TextView
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="test" />
<TextView
android:layout_width="10dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:text="test" />
</LinearLayout>
重新指向另外一个对象横向排列三个textview,设置layout_weight比值为1:2:3,呈现效果如下:
可以看到宽度并没有按照1:2:3的比例,其原因还是剩余空间概念的问题。假设屏幕像素为480dp,那么第一个textview的宽度为10dp,第二个textview的宽度为100dp,第三个textview的宽度为10dp,那么此时剩余空间则为480-10-100-10=360dp,再按照1:2:3比例来算,第一个textview分到60dp,加上原有10dp的则是70dp,同理第二个为220dp,第三个看度为190dp,所以最终比例如图7:22:9。
相信通过该例子对于layout_weight的属性已经有了一定了解。那么如何实现真正的按比值设置宽度呢?设置layout_width均为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:layout_centerVertical="true"
android:minHeight="@dimen/listitem_min_height">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="test" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="test" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:text="test" />
</LinearLayout>
属性的了解不能一知半解,否则事倍功半。了解原理很重要。
特记下,以备后日回顾。