android:layout_weight總有你不知道的用法.


  都知道weight是權重的意思. 在布局中起到非常重要的作用. 但是這玩意不能嵌套使用, 而且只能使用在LinearLayout中.

  下面說說它的幾種用法(以下例子全為橫排 注意android:layout_width值和android:layout_weight值的變化)  

  第一種, 最普遍的-----均分, weight的值越大, 占的空間越大.注意android:layout_width的值都為0dp

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <FrameLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#000" />

    <Button
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"/>

    <FrameLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#888" />

</LinearLayout>

   第二種, 占滿剩余空間, 不管是否處在最后一個

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <FrameLayout
        android:layout_width="40dp"
        android:layout_height="match_parent"
        android:background="#000" />

    <Button
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"/>

    <FrameLayout
        android:layout_width="40dp"
        android:layout_height="match_parent"
        android:background="#888" />

</LinearLayout>

   第三種, 值越大占的空間越小, 值為同布局下其它控件的weight之和時,即消失.注意android:layout_width的值都為match_parent為0時占滿. 有什么用途? 呵呵, 存在即是合理的. 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#000" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1.5"/>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#000" />

</LinearLayout>

 

   最后一種(我會用的), 結合android:weightSum使用, 那這兒就用一個問題引入, 如何將控件放在屏幕的中央, 寬度為屏幕的一半?  嗯.....想啊.....想啊...RelativeLayout? 哦, 沒法控制? 哦,只能代碼了... 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:weightSum="2">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>

</LinearLayout>

 

 ok, so easy!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM