Android的LinearLayout中的權重android:layout_weight

來源:互聯網
上載者:User

標籤:

當前EditText和Button組件只是適應了他們各自內容的大小,如所示:

這樣設定對按鈕來說很合適,但是對於文字框來說就不太好了,因為使用者可能輸入更長的常值內容。因此如果能夠佔滿整個螢幕寬度會更好。LinearLayout使用權重屬性來達到這個目的,你可以使用android:layout_weight屬性來設定。

權重的值指的是每個組件所佔剩餘空間的大小,該值與同級組件所佔空間大小有關。就類似於飲料的成分配方:“兩份伏特加酒,一份咖啡利口酒”,即該酒中伏特加酒佔三分之二。例如,我們設定一個View的權重是2,另一個View的權重是1,那麼總數就是3,這時第一個View佔據2/3的空間,第二個佔據1/3的空間。如果你再加入第三個View,權重設為1,那麼第一個View(權重為2的)會佔據1/2的空間,剩餘的另外兩個View各佔1/4。(請注意,使用權重的前提一般是給View的寬或者高的大小設定為0dp,然後系統根據上面的權重規則來計算View應該佔據的空間。但是很多情況下,如果給View設定了match_parent的屬性,那麼上面計算權重時則不是通常的正比,而是反比,也就是權重值大的反而佔據空間小)。

對於所有的View預設的權重是0,如果只設定了一個View的權重大於0,則該View將佔據除去別的View本身佔據的空間的所有剩餘空間。因此這裡設定EditText的權重為1,使其能夠佔據除了按鈕之外的所有空間。

 

設定權重後的

現在看一下完整的布局檔案內容:

res/layout/activity_my.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="horizontal">    <EditText android:id="@+id/edit_message"        android:layout_weight="1"        android:layout_width="0dp"        android:layout_height="wrap_content"        android:hint="@string/edit_message" />    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/button_send" /></LinearLayout>

Android的LinearLayout中的權重android:layout_weight

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.