Android LinearLayout的android:layout_weight屬性

來源:互聯網
上載者:User

標籤:android   blog   http   java   strong   width   

本文主要介紹 Android LinearLayout的android:layout_weight屬性意義

 

android:layout_weight為大小權重,相當於在頁面上顯示的百分比,它的計算是根據LinearLayout中所有相關元素的此屬性值計算的。

除了已經固定大小的,其他設定了此屬性的view所佔大小(長度或高度)為自己layout_weight屬性值/所有layout_weight屬性值*總大小。這個屬性在android的sdk中都沒有介紹。下面舉例介紹下

 

比如在一個layout中顯示3個TextView,第一個TextView長度佔20%,第二個長度佔50%,第三個占長度30%,

則比例為20%:50%:30%=2:5:3。layout代碼如下

Java代碼  
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout  
  3.     xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent">     
  6.     <TextView android:id="@+id/textView1"     
  7.         android:layout_width="wrap_content"     
  8.         android:layout_height="match_parent"     
  9.         android:layout_weight="2"  
  10.         android:layout_alignParentLeft="true"  
  11.         android:gravity="center_vertical"  
  12.         android:text="文本1" />   
  13.     <TextView android:id="@+id/textView2"     
  14.         android:layout_width="wrap_content"     
  15.         android:layout_height="match_parent"     
  16.         android:layout_weight="5"  
  17.         android:layout_alignParentLeft="true"  
  18.         android:gravity="center_vertical"  
  19.         android:text="文本2" />   
  20.     <TextView android:id="@+id/textView3"     
  21.         android:layout_width="wrap_content"     
  22.         android:layout_height="match_parent"     
  23.         android:layout_weight="3"  
  24.         android:layout_alignParentLeft="true"  
  25.         android:gravity="center_vertical"  
  26.         android:text="文本3" />   
  27. </LinearLayout>  

從以上代碼可以看出只需要設定各個TextView的android:layout_weight屬性值為對應的比例即可

其中android:layout_alignParentLeft="true" android:gravity="center_vertical"是為了方便查看而設定

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.