<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">还在学校时,老师介绍布局时,权重这个属性很轻微的带过了,我就只知道他能够分配各布局的大小空间。由于使用并不多,老师也不做重点,当时也没太在意。到现在出来工作时,接触的项目多了,对这属性使用也多了。当然,你去了解这个属性可以有很多种途径,最好的途径是去浏览源码,或者去看官方的API文档,等等·。现在我要介绍的一种方法是从现象进行归纳。</span>
归纳法,我最早接触的时候是小学的数学题,比如1,3,5,7,【】,11,13,填补空缺的数。这就是最典型的归纳法。但由于太过简单,往往会被人忽视。其实,归纳法在数学科学中占有很重要的位置。废话不多说。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:layout_weight="2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/app_name"
android:background="#00ff00"/>
<TextView
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/app_name"
android:background="#ff0000"/>
</LinearLayout>
可以看到这段代码的效果是这样的
权重值大的View反而分配的空间小,而且比例是1:2
接着,我对源代码做出些小改动:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:layout_weight="2"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="@string/app_name"
android:background="#00ff00"/>
<TextView
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="@string/app_name"
android:background="#ff0000"/>
</LinearLayout>
如果细心观察就看出,两个TextView的
layout_width属性由原来的
match_parent改成了
wrap_content,再让我们看看结果
跟上者恰恰相反,权重大的分配空间越大。
可以看出,需求空间越大的,权重越大,分配空间越小。
当然,归纳法需要大量证据,在这,我就不一一列举了。