Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 新手筆記(21):百分比佈局 PercentLayout 使用說明

編輯:關於 Android 程式設計

傳統佈局靠 wrap_content、match_parent 加權重來分配空間,遇到需要嚴格按比例排布的界面就比較吃力。百分比佈局允許直接用百分比指定控件的寬高,寫起來直觀得多。

一、添加依賴

在 app/build.gradle 中引入 percent 庫:

compile 'com.android.support:percent:25.1.1'

注意這裡的版本號需要與項目中其他 support 庫保持一致,否則容易出現資源或依賴衝突。完整的 dependencies 大致如下:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.1.1'
    compile 'com.android.support:percent:25.1.1'
    testCompile 'junit:junit:4.12'
}

修改 gradle 文件後,IDE 通常會提示 Gradle files have changed since last project sync,點擊 Sync Now 完成同步即可。

二、基本用法

根佈局換成 PercentRelativeLayout,控件的寬高改用 app:layout_widthPercent 與 app:layout_heightPercent 指定,配合 android:layout_gravity 定位:

<android.support.percent.PercentRelativeLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button1"
        android:layout_gravity="left|top"
        android:text="Button"
        app:layout_widthPercent="50%"
        app:layout_heightPercent="50%" />

    <Button
        android:id="@+id/button2"
        android:layout_gravity="right|top"
        android:text="Button"
        app:layout_widthPercent="50%"
        app:layout_heightPercent="50%" />

    <Button
        android:id="@+id/button3"
        android:layout_gravity="left|bottom"
        android:text="Button"
        app:layout_widthPercent="50%"
        app:layout_heightPercent="50%" />

    <Button
        android:id="@+id/button4"
        android:layout_gravity="right|bottom"
        android:text="Button"
        app:layout_widthPercent="50%"
        app:layout_heightPercent="50%" />
</android.support.percent.PercentRelativeLayout>

上面這段的效果是屏幕被四等分,四個按鈕各佔一個象限。除了百分比寬高,percent 庫還提供 app:layout_aspectRatio 來按固定寬高比縮放控件,在處理圖片、視頻封面等場景時特別省事。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved