1. 程式人生 > >Android開發之layout_weight屬性的應用

Android開發之layout_weight屬性的應用

在Android開發過程中,Android開發者之間的交流學習是互通開源的。關於Android開發中layout佈局檔案中常用到的屬性,有很多小盆友不瞭解,今天就來為童鞋們整理分享如下內容:

在layout佈局檔案中經常用到android:layout_width、android:layout_width及android:layout_weight這些屬性。那麼android:layout_weight代表什麼呢?不要譯為體重,重量。Weight也可表示比重、權重,這在測量學中比較常見。

預設值為0,即檢視大小與螢幕空間大小相等,螢幕有多大,檢視就有多大。如果將其設為大於0的數值,則將父檢視的可用空間分割,分割大小具體取決於每個檢視的layout_weight的值,該值在當前屏幕布局的整體 layout_weight值和在其它檢視屏幕布局的layout_weight值中所佔的比率而定。

打個比方,水平佈局有兩個圖片,一個圖片值為1,另一個圖片值也為1,則兩者平分檢視;或者一個圖片值為1,另一個圖片值為2,則第一個圖片所佔檢視為2/3,第二張圖片所佔檢視為1/3。

1、程式碼:

< ImageView 

        android:id="@+id/imageView1" 

        android:layout_width="wrap_content"         android:layout_height="wrap_content"                android:layout_weight="1"         android:tint="#33ff9966" 

        android:src="@drawable/c" />   

  <ImageView 

        android:id="@+id/imageView2" 

        android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_weight="1"         android:src="@drawable/c" />

效果:


2、程式碼:在佈局檔案中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 

    android:orientation="vertical" 

    android:layout_width="fill_parent" 

    android:layout_height="fill_parent" 

    >  

  <LinearLayout  

      android:orientation="horizontal" 

      android:layout_width="fill_parent" 

      android:layout_height="fill_parent" 

      android:layout_weight="1">  

      <TextView  

          android:text="redwwwwwww" 

          android:gravity="center_horizontal" 

          android:background="#aa0000" 

          android:layout_width="wrap_content" 

          android:layout_height="fill_parent" 

          android:layout_weight="1"/>  

      <TextView  

          android:text="green" 

          android:gravity="center_horizontal" 

          android:background="#00aa00" 

          android:layout_width="wrap_content" 

          android:layout_height="fill_parent" 

          android:layout_weight="2"/>  

      <TextView  

          android:text="blue" 

          android:gravity="center_horizontal" 

          android:background="#0000aa" 

          android:layout_width="wrap_content" 

          android:layout_height="fill_parent" 

          android:layout_weight="3"/>  

      <TextView  

          android:text="yellow" 

          android:gravity="center_horizontal" 

          android:background="#aaaa00" 

          android:layout_width="wrap_content" 

          android:layout_height="fill_parent" 

          android:layout_weight="4"/>  

  </LinearLayout>  

</LinearLayout>

效果:

我不明白這個是怎麼佈設的,權重又該怎麼算。有人明白的話給我指點迷津。