天天看點

android布局之layout_weight應用

    layout_weight用于将所有子控件按weight的比例來配置設定布局,該屬性隻能用于TableLayout和LinearLayout。

    比如我想把LinearLayout的幾個子控件均分,那麼可以設定每個子控件的layout_weight為1:

<LinearLayout
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:text="控件1"
        android:id="@+id/textView8"
        android:layout_weight="1" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:text="控件2"
        android:id="@+id/textView9"
        android:layout_weight="1" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:text="控件3"
        android:id="@+id/textView10"
        android:layout_weight="1" />
</LinearLayout>      

    子控件占用的大小為該控件的weight占所有子控件的比例。上面的例子3個控件的weight都為1,是以大小是均分的。

    另外要注意,設定了weight後,把width或height設定為0dp。如果是水準布局設定width為0dp,垂直布局設定height為0dp。

    不設定為0dp有什麼問題?我試驗過如果該控件内如果還嵌套子控件的話,會導緻不能按所設定weight正确劃分占用的空間。使用weight要注意該事項。

繼續閱讀