在为LinearLayout的ViewGroup下的View设置其layout_weight属性时候,需要LinearLayout的layout_width(当orientation是horizontal)或者layout_height的属性(当orientation为vertical时)是fill_parent,而且其子view的layout_width或者layout_height属性(依据orientation的设置)其值必须是0,这样你为子view设置的layout_weight属性才会发挥其“比重”或者称“权重”的作用。以前以为应该将子view的layout_width或者layout_height设置为fill_parent,而且在当所有的view的权重是一样的时候的表现确实跟想象的一样,也就是说在一个LinearLayout下的子view的权重都是相同的情况下,为其layout_width或者layout_height设置为fill_parent以后,其表现效果确实是“在该LinearLayout下的所有view平分了该LinearLayout的空间”。但是当需要子view的权重不一样时候比如这样的场景:
在一个LinearLayout中有三个文本框,垂直线性排列,其比例为:1:1:2。
按照以前的想法,布局如下:
<?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:orientation="vertical"
android:weightSum="4"
>
<EditText
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="我占整个屏幕的1/4"
android:layout_weight="1"
/>
<EditText
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="我占整个屏幕的1/4"
android:layout_weight="1"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="2"
android:text="我占整个屏幕的1/2"
/>
</LinearLayout>
但是实际表现效果是:
第一个和第二个分别占了整个屏幕的1/2,第三个未显示,诸位可以自己尝试一下。
将这三个view的layout_height属性该为"android:layout_height="0dp""之后,达到了预期效果~~
如图:
以下是官方文档中的描述:
To create a proportionate size layout on the screen, create a container view group object with the layout_width and layout_height attributes set tofill_parent; assign the children height or width to 0(zero); then assign relative weight values to each child, depending on what proportion of the screen each should have.