Android開發技巧之使用weight屬性實現控制項的按比例分配空間

來源:互聯網
上載者:User

標籤:android

從今天開始,把看書時候的知識點整理成部落格,

這個比較簡單,估計有經驗的都用過,weight屬性

 

在做Android布局的時候,經常遇到需要幾個控制項按比例分配空間的情況

比如效果

在底部設定兩個button,佔據底部寬度一部分的同時,保持1:3的比例,

當然了,這麼難看的布局用處不大,僅是用來說明weight的用法

布局代碼如下:

<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:weightSum="6"    android:gravity="bottom|center_horizontal" >    <Button        android:id="@+id/bn_main_left"        android:layout_width="0dp"        android:layout_height="wrap_content"        android:layout_weight="1"        android:text="left" />    <Button        android:id="@+id/bn_main_right"        android:layout_width="0dp"        android:layout_height="wrap_content"        android:layout_weight="3"        android:text="right" /></LinearLayout>


其中LinearLayout裡面有個weightSum,這個屬性是用來設定LinearLayout的weight總和,

Button裡面的layout_weight就是用來設定button佔據LinearLayout的空間的大小

 

形象一點說,LinearLayout像一個盒子,weightSum設定了盒子的大小為6,

往盒子裡放了兩個button,給左邊button設定layout_weight="1",佔據1/6空間,

右邊button設定了layout_weight="3",佔據3/6空間

這樣兩個button加起來佔據了LinearLayout的4/6,

 

如果沒有給LinearLayout設定weightSum的話,則預設為所有控制項layout_weight的總和.

 

jason0539

微博:http://weibo.com/2553717707

部落格:http://blog.csdn.net/jason0539(轉載請說明出處)

相關文章

聯繫我們

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