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

Android 螢幕適配完全筆記:從 dpi、dp、權重到百分比佈局

編輯:關於 Android 程式設計

一、先建立正確的基礎概念

跌跌撞撞也好,摸爬滾打也罷,在 Android 開發圈子裡徘徊一年多以來,發現自己對不少基礎概念其實並不清楚。現在正是回到更貼近底層的地方,把它們補起來的時候。

Android 系統的硬體覆蓋了電子產品的方方面面,螢幕規格 therefore 高度多樣化,這也是 Android 碎片化的重要成因。碎片化是難題,但不代表開發時可以不做兼容——螢幕適配正是其中不可迴避的一環。

市面上至今沒有一勞永逸、一次適配全部的完美方案,但我們可以用現有的技術手段把 App 的適配程度不斷推向更好。以下聊聊實務上的處理方式。

1. 幾個關鍵詞

dpi(dot per inch):像素密度比,指單位物理長度下的像素數量。

dp / dip:螢幕無關像素。它既不是物理長度也不是像素點,只有在確定的像素密度比下才能換算成像素:dp × dpi = px。手機一旦定型,dpi 固定,dp 也就跟著確定。

螢幕解析度:螢幕寬與高的像素數。常見檔次大致有 1920×1080(xxhdpi)、1280×720(xhdpi)、960×540 / 800×400 / 854×480(hdpi)、480×320(mdpi)、240×320(ldpi)。

各密度之間的比例關係為 ldpi : mdpi : hdpi : xhdpi : xxhdpi = 3 : 4 : 6 : 8 : 12。

不同像素密度下,圖示的合理尺寸也不同:

2. 什麼叫「適配」

簡單說:程式運行時,在不同硬體上都能呈現接近設計稿的效果。

不適配的典型樣貌是:帶文字的元件寬度不夠、文字顯示不全;圖示、Bar、按鈕過大或過小。

我把它拆成兩個面向:

(1)同一解析度下,不同螢幕尺寸(手機 → 平板 → 電視);
(2)同一螢幕尺寸下,不同螢幕解析度。

第一種情況,實務上多半直接另開一個 App 處理,因為螢幕差距已經大到「質變」,頁面結構與業務邏輯幾乎是兩個產品。在同一個 App 裡硬做當然也行,但維護與實作成本往往比另開一個更高。

手機雖然也有多種尺寸,但彼此差距不大、長寬比例接近,所以通常歸類到第二種情況一起處理。以下就聚焦在同一硬體尺寸下的適配。

二、具體的適配手段

1. 佈局層面

多用 LinearLayout、RelativeLayout,別再用已被淘汰的絕對佈局。

2. 元件屬性

多用 match_parent / wrap_content;尺寸單位用 dp、文字用 sp,不要用 px(Android Studio 已經會提示)。

3. 權重(layout_weight)

當寬度或高度設為 0dp 時搭配 layout_weight,讓父容器依權重比例分配對應的高度或寬度:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- 佈局適配 -->
    <TextView
        android:id="@+id/desc_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="布局適配"
        android:textSize="26sp" />

    <EditText
        android:id="@+id/body_et"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/desc_1" />

    <Button
        android:id="@+id/body_ensure"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/body_et"
        android:layout_alignParentRight="true"
        android:text="確認"
        android:textSize="26sp" />

    <Button
        android:id="@+id/body_search"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/body_et"
        android:layout_toLeftOf="@+id/body_ensure"
        android:text="搜索"
        android:textSize="26sp" />

    <!-- 單位適配 -->
    <View
        android:id="@+id/divider"
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:layout_below="@+id/body_search"
        android:background="@color/red" />

    <TextView
        android:id="@+id/desc_2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/divider"
        android:text="單位適配"
        android:textSize="26sp" />

    <Button
        android:id="@+id/bt1"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/desc_2"
        android:text="dp"
        android:textSize="26sp" />

    <Button
        android:layout_width="200px"
        android:layout_height="wrap_content"
        android:layout_below="@+id/desc_2"
        android:layout_toRightOf="@+id/bt1"
        android:text="px"
        android:textSize="26sp" />

    <!-- 權重適配:水平 -->
    <LinearLayout
        android:id="@+id/ll_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/desc_3"
        android:orientation="horizontal">

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="橫向權重:1"
            android:textSize="26sp" />

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="橫向權重:1"
            android:textSize="26sp" />
    </LinearLayout>

    <!-- 權重適配:垂直 -->
    <LinearLayout
        android:id="@+id/ll_2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:text="縱向權重:1"
            android:textSize="26sp" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:text="縱向權重:1"
            android:textSize="26sp" />
    </LinearLayout>
</RelativeLayout>

適配效果:

佈局適配:

整體效果:

單位適配(dp 與 px 的對比最能說明問題):

4. 硬體單位化(生成 lay_x / lay_y)

思路是把螢幕虛擬地劃分成固定份數。以 320×480 為基準,為每一種解析度產生對應的 dimen 資源檔,使用時直接引用 @dimen/x240 這類「虛擬座標」,就能做到像素級還原設計稿。

public class MakeXml {

    private final static String rootPath = "C:\\Users\\Administrator\\Desktop\\layoutroot\\values-{0}x{1}\\";
    private final static float dw = 320f;
    private final static float dh = 480f;
    private final static String WTemplate = "<dimen name=\"x{0}\">{1}px</dimen>\n";
    private final static String HTemplate = "<dimen name=\"y{0}\">{1}px</dimen>\n";

    public static void main(String[] args) {
        makeString(320, 480);
        makeString(480, 800);
        makeString(480, 854);
        makeString(540, 960);
        makeString(600, 1024);
        makeString(720, 1184);
        makeString(720, 1196);
        makeString(720, 1280);
        makeString(768, 1024);
        makeString(768, 1280);   // nexus 4
        makeString(800, 1280);
        makeString(1080, 1812);
        makeString(1080, 1920);
        makeString(1440, 2560);
        makeString(1536, 2048);  // nexus 9
        makeString(2560, 1600);  // nexus 10
    }

    public static void makeString(int w, int h) {
        StringBuffer sb = new StringBuffer();
        sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
        sb.append("<resources>");
        float cellw = w / dw;
        for (int i = 1; i < 320; i++) {
            sb.append(WTemplate.replace("{0}", i + "")
                    .replace("{1}", change(cellw * i) + ""));
        }
        sb.append(WTemplate.replace("{0}", "320").replace("{1}", w + ""));
        sb.append("</resources>");

        StringBuffer sb2 = new StringBuffer();
        sb2.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
        sb2.append("<resources>");
        float cellh = h / dh;
        for (int i = 1; i < 480; i++) {
            sb2.append(HTemplate.replace("{0}", i + "")
                    .replace("{1}", change(cellh * i) + ""));
        }
        sb2.append(HTemplate.replace("{0}", "480").replace("{1}", h + ""));
        sb2.append("</resources>");

        String path = rootPath.replace("{0}", h + "").replace("{1}", w + "");
        File rootFile = new File(path);
        if (!rootFile.exists()) {
            rootFile.mkdirs();
        }
        File layxFile = new File(path + "lay_x.xml");
        File layyFile = new File(path + "lay_y.xml");
        try {
            PrintWriter pw = new PrintWriter(new FileOutputStream(layxFile));
            pw.print(sb.toString());
            pw.close();
            pw = new PrintWriter(new FileOutputStream(layyFile));
            pw.print(sb2.toString());
            pw.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /** 保留兩位小數 */
    public static float change(float a) {
        int temp = (int) (a * 100);
        return temp / 100f;
    }
}

把產生的檔案放到 res/ 目錄下:

使用方式:

<Button
    android:layout_width="@dimen/x160"
    android:layout_height="@dimen/x240" />

效果:

弊端很明確:遇到沒有產生對應解析度檔案的機型(例如 Nexus 7),畫面會直接空白;而且這些檔案一直留在 App 裡,相對耗儲存空間。

5. 圖片適配

依不同解析度切出對應的圖片,就能解決背景、按鈕、圖示、TabBar、Icon 的適配問題。切圖比例參考:

為了控制 App 體積,多套圖並不建議。實務上常切成大圖,再搭配市佔率最高的兩套來覆蓋全部機型。

圖片適配的整體流程:

另外也可以採用 .9 圖(NinePatch)。製作時請注意每邊都保留 2px,不要讓邊框線完全貼齊;同時標好拉伸區域與內容區域,讓最核心的圖形保持合理變形,整體縮放符合視覺預期。

Android SDK 自帶 9-Patch 編輯工具,位於 tools 目錄下的 draw9patch.bat,可以即時預覽拉伸效果。

6. 百分比佈局

瀏覽器裡的 Web 頁面螢幕變化不比手機少,卻很少出現適配問題,原因就是大量使用比例佈局。Android 5.0 之後提供了百分比佈局:

<RelativeLayout 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/bt1"
        android:layout_width="200dp"
        android:layout_height="match_parent"
        android:text="百分布局的固定寬度"
        android:textSize="18sp" />

    <Button
        android:id="@+id/bt2"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_toRightOf="@+id/bt1"
        android:background="@color/blue"
        android:text="比例:50%"
        android:textSize="20sp"
        app:layout_widthPercent="50%" />

    <Button
        android:id="@+id/bt4"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:background="@color/green"
        android:text="比例:30%"
        android:textSize="20sp"
        app:layout_widthPercent="30%" />

    <Button
        android:id="@+id/bt7"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_below="@+id/bt1"
        android:text="縱向百分布局:20%"
        app:layout_heightPercent="20%" />
</RelativeLayout>

效果:

要留意的是,百分比是相對於父容器的屬性計算的。所以一旦摻入了固定長度的元件(如圖中第一行),仍然無法完全適配;只有在所有元件都按 100% 完整切分父容器屬性的情況下,百分比佈局的適配性才最好。

實際專案裡,這幾種手段通常混用:結構用百分比與權重打底,圖片用 .9 圖與少量切圖補齊,實在無法避免的像素級還原再考慮 lay_x / lay_y 方案。

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