編輯:關於 Android 開發
螢幕適配大概是 Android 開發者共同的痛。同一份配置檔,在這支手機上完美,換一支就錯位;同一張切圖,在這台清晰銳利,換一台就模糊發虛。本文以 Google 官方文件為基礎,把適配的成因、關鍵概念、解法與實務經驗一次講清楚。
Android 的開放性既是優勢也是負擔。任何使用者、開發者、OEM 廠商、電信業者都能改造它,結果就是極度嚴重的碎片化。
OpenSignalMaps 曾發布過幾份經典的碎片化統計:2012 年支援 Android 的裝置約 3997 種,2013 年增至 11868 種,2014 年已達 18796 種。下面這張圖裡的每一個方塊,都代表著一款真實存在的裝置。

手機、平板、電視、手錶……裝置數量持續攀升,裝置碎片化、品牌碎片化、系統碎片化、感測器碎片化與螢幕碎片化也一併加深。其中對開發影響最直接的就是螢幕碎片化。
下圖以方塊大小代表不同螢幕尺寸、深淺代表佔比:

對照之下,iOS 需要處理的尺寸就只有寥寥數種(何況後來新增的 iPhone 6 與 Plus 也仍在可控範圍):

差距一目了然。這就是為什麼我們必須在開發階段就處理適配。
那麼,從幾吋的手機到幾十吋的電視,難道都要顧到嗎?其實不必這麼想。在像素密度相同的前提下,解析度越高螢幕就越大,所以把問題從「尺寸」換成「解析度 + 密度」來看會清楚得多。
2014 年初友盟統計中佔比超過 5% 的六種主流解析度裡,480×800 居首,320×480 也佔了可觀比例。與半年前相比,中低解析度份額在退,中高解析度在漲,但名單大致沒變。也就是說,把這幾種主流解析度顧好,就能覆蓋絕大多數手機;平板與電視則需要另外處理。

指螢幕對角線長度,單位是英吋,1 英吋 = 2.54 公分。常見的有 2.4、2.8、3.5、3.7、4.2、5.0、5.5、6.0 等。
指橫向與縱向的像素點數,單位 px,1px = 一個像素點,一般寫成「縱向 × 橫向」,例如 1920×1080。
指每英吋上的像素點數,單位 dpi(dot per inch)。它同時受螢幕尺寸與解析度影響:尺寸不變而解析度越高,密度越大;解析度不變而尺寸越小,密度也越大。
px 大家最熟,UI 設計稿與多數 Android 原生 API 都以它為單位,像是取得螢幕寬高。
dip 與 dp 是同一件事,都是 Density Independent Pixels(密度無關像素)的縮寫。Android 規定以 160dpi 為基準,此時 1dp = 1px;密度 320dpi 時,1dp = 2px,以此類推。
實感一下差別:同樣畫一條 320px 的線,在 480×800 的機型上佔畫面三分之二寬,在 320×480 上卻佔滿整屏;改用 dp 當單位後,160dp 在兩者上都剛好是半個螢幕寬。這正是配置檔裡該用 dp 而非 px 的根本原因。
sp(scale-independent pixels)與 dp 類似,但會隨使用者的「字型大小」偏好縮放,是設定字級的專用單位。
ldpi 在當今裝置上已近乎絕跡,適配時可不必費神(系統會自動把 hdpi 圖示縮小一半去頂替)。這幾個名稱用來修飾 drawable 與 values 資料夾,區分不同密度下的圖片與 dimen 值。Google 的分類標準如下:
| 名稱 | 像素密度範圍 |
|---|---|
| mdpi | 120dpi ~ 160dpi |
| hdpi | 160dpi ~ 240dpi |
| xhdpi | 240dpi ~ 320dpi |
| xxhdpi | 320dpi ~ 480dpi |
| xxxhdpi | 480dpi ~ 640dpi |
設計圖示時,五種主流密度應按 2 : 3 : 4 : 6 : 8 的比例縮放。例如一個 48×48dp 的啟動圖示,在 mdpi 上就是 48×48px,hdpi 是 1.5 倍(72×72px),xhdpi 是 2 倍(96×96px),依此類推:

| 螢幕密度 | 圖示尺寸 |
|---|---|
| mdpi | 48×48px |
| hdpi | 72×72px |
| xhdpi | 96×96px |
| xxhdpi | 144×144px |
| xxxhdpi | 192×192px |
要讓版面有彈性,第一原則是別寫死尺寸。wrap_content 會讓 View 收縮到剛好容納內容;match_parent(API 8 以下稱 fill_parent)則讓它撐滿父容器。兩者搭配使用,版面就能自動適應各種螢幕與方向。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:id="@+id/linearLayout1"
android:gravity="center"
android:layout_height="50dp">
<ImageView
android:id="@+id/imageView1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="@drawable/logo"
android:paddingRight="30dp"
android:layout_gravity="left"
android:layout_weight="0" />
<View
android:layout_height="wrap_content"
android:id="@+id/view1"
android:layout_width="wrap_content"
android:layout_weight="1" />
<Button
android:id="@+id/categorybutton"
android:background="@drawable/button_bg"
android:layout_height="match_parent"
android:layout_weight="0"
android:layout_width="120dp"
style="@style/CategoryButtonStyle" />
</LinearLayout>
<fragment
android:id="@+id/headlines"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.HeadlinesFragment"
android:layout_width="match_parent" />
</LinearLayout>
橫竖屏切換時的表現:

weight 是 LinearLayout 的專屬屬性,用來按比例分配空間。最常見的用法是兩個寬度設為 0dp 的按鈕,weight 分別給 1 和 2:

結果就是 1:2 的寬度比,Button1 佔 1/(1+2)=1/3,Button2 佔 2/3,很直觀。
但如果把 layout_width 改成 match_parent 呢?

比例竟然反過來了。原因在於 weight 的真實語意:最終寬度 = 原有寬度(layout_width)+ 剩餘空間 × 權重佔比。
設螢幕寬為 L,兩個按鈕寬度都是 match_parent,也就是各佔 L,剩餘空間 = L − (L + L) = −L。Button1 的 weight 為 1,佔比 1/3,最終寬度 = L + 1/3 × (−L) = 2/3 L;Button2 則是 L + 2/3 × (−L) = 1/3 L。這就解釋了為何結果顛倒。
垂直方向的行為完全相同,只是改動 layout_height:
0dp 的情況:
match_parent 的情況:
結論一樣。不過實務上我們幾乎都會把某一維度設為 0dp,再靠權重切百分比,這樣語意最清楚、也最不容易出錯。
絕對配置(AbsoluteLayout)適配能力極差,早已被官方標記為 deprecated,不建議使用。日常開發主要還是在 LinearLayout、RelativeLayout 與 FrameLayout 之間取捨。
LinearLayout 可以透過嵌套組出相當複雜的版面,但它只能把子 View 排成一條直線,無法描述「A 在 B 旁邊、C 對齊右側」這類關係。這時 RelativeLayout 才是正解——它能依元件間的相對關係定位。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Type here:"/>
<EditText
android:id="@+id/entry"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/label"/>
<Button
android:id="@+id/ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/entry"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dp"
android:text="OK" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/ok"
android:layout_alignTop="@id/ok"
android:text="Cancel" />
</RelativeLayout>
小螢幕上的顯示:

平板大螢幕上的顯示:

元件尺寸雖然隨螢幕變了,但彼此的相對關係沒有跑掉——這就是相對配置的價值。
彈性配置能做的就到這裡。它會拉伸、會壓縮,但不保證每種螢幕都拿到最佳體驗。所以除了單一配置,我們還該針對不同螢幕配置準備備用版面,透過配置限定符讓系統在執行期自動挑選。
最典型的例子是「雙面板」模式:平板與電視螢幕夠大,左側列清單、右側顯示內容;手機則得拆成兩頁。
res/layout/main.xml(單面板,預設):
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:id="@+id/headlines"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.HeadlinesFragment"
android:layout_width="match_parent" />
</LinearLayout>
res/layout-large/main.xml(雙面板):
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<fragment android:id="@+id/headlines"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.HeadlinesFragment"
android:layout_width="400dp"
android:layout_marginRight="10dp"/>
<fragment android:id="@+id/article"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.ArticleFragment"
android:layout_width="fill_parent" />
</LinearLayout>
注意目錄名中的 large 限定符。系統會在較大螢幕(約 7 吋以上平板)上選它,其他情況則退回無限定符的預設版本。
Android 3.2 以前的「較大」屏幕定義太粗——戴爾 Streak、初代 Galaxy Tab 與多數 7 吋平板都被歸在同一類,但 5 吋與 7 吋顯然該有不同版面。因此 3.2 引入了「最小寬度」限定符。
最小寬度以 dp 為單位描述螢幕。標準 7 吋平板的最小寬度是 600dp,於是只要把雙面板版本放在 layout-sw600dp/ 下,就能精準命中:
res/layout/main.xml(單面板,預設):
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:id="@+id/headlines"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.HeadlinesFragment"
android:layout_width="match_parent" />
</LinearLayout>
res/layout-sw600dp/main.xml(雙面板):
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<fragment android:id="@+id/headlines"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.HeadlinesFragment"
android:layout_width="400dp"
android:layout_marginRight="10dp"/>
<fragment android:id="@+id/article"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.ArticleFragment"
android:layout_width="fill_parent" />
</LinearLayout>
最小寬度 ≥ 600dp 的裝置會命中 layout-sw600dp,其餘走 layout。但 3.2 以下的系統讀不懂 sw600dp,仍得靠 large,於是同一份雙面板配置檔就要維護兩份——這就引出下一個技巧。
如果同時要相容 3.2 以上與以下,你手上會有三個檔案:layout/main.xml(單面板)、layout-large/(多面板)、layout-sw600dp/(多面板)。後兩者內容完全相同,卻得分開維護。
解法是把實際配置抽出來,再用別名指向它:
先準備兩個真正的配置檔:res/layout/main.xml(單面板)與 res/layout/main_twopanes.xml(雙面板)。接著各加一個別名檔:
res/values-large/layout.xml:
<resources>
<item name="main" type="layout">@layout/main_twopanes</item>
</resources>
res/values-sw600dp/layout.xml:
<resources>
<item name="main" type="layout">@layout/main_twopanes</item>
</resources>
兩份內容一樣,但它們並未定義任何版面,只是把 main 指向 main_twopanes。由於同時帶有 large 與 sw600dp 選擇器,無論系統版本都能正確命中平板與電視。
同一個尺寸,橫向與縱向的最佳版面往往不同。以新聞閱讀器為例:
先把所有可能的版面都寫進 res/layout/:
res/layout/onepane.xml(單面板):
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:id="@+id/headlines"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.HeadlinesFragment"
android:layout_width="match_parent" />
</LinearLayout>
res/layout/onepane_with_bar.xml(單面板帶操作列):
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:layout_width="match_parent"
android:id="@+id/linearLayout1"
android:gravity="center"
android:layout_height="50dp">
<ImageView android:id="@+id/imageView1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="@drawable/logo"
android:paddingRight="30dp"
android:layout_gravity="left"
android:layout_weight="0" />
<View android:layout_height="wrap_content"
android:id="@+id/view1"
android:layout_width="wrap_content"
android:layout_weight="1" />
<Button android:id="@+id/categorybutton"
android:background="@drawable/button_bg"
android:layout_height="match_parent"
android:layout_weight="0"
android:layout_width="120dp"
/>
</LinearLayout>
<fragment android:id="@+id/headlines"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.HeadlinesFragment"
android:layout_width="match_parent" />
</LinearLayout>
res/layout/twopanes.xml(雙面板,寬版面):
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<fragment android:id="@+id/headlines"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.HeadlinesFragment"
android:layout_width="400dp"
android:layout_marginRight="10dp"/>
<fragment android:id="@+id/article"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.ArticleFragment"
android:layout_width="fill_parent" />
</LinearLayout>
res/layout/twopanes_narrow.xml(雙面板,窄版面,僅左欄寬度不同):
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<fragment android:id="@+id/headlines"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.HeadlinesFragment"
android:layout_width="200dp"
android:layout_marginRight="10dp"/>
<fragment android:id="@+id/article"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.ArticleFragment"
android:layout_width="fill_parent" />
</LinearLayout>
最後,用別名把版面映射到各配置上。預設值:
res/values/layouts.xml:
<resources>
<item name="main_layout" type="layout">@layout/onepane_with_bar</item>
<bool name="has_two_panes">false</bool>
</resources>
res/values-sw600dp-land/layouts.xml:
<resources>
<item name="main_layout" type="layout">@layout/twopanes</item>
<bool name="has_two_panes">true</bool>
</resources>
res/values-sw600dp-port/layouts.xml:
<resources>
<item name="main_layout" type="layout">@layout/onepane</item>
<bool name="has_two_panes">false</bool>
</resources>
res/values-large-land/layouts.xml:
<resources>
<item name="main_layout" type="layout">@layout/twopanes</item>
<bool name="has_two_panes">true</bool>
</resources>
res/values-large-port/layouts.xml:
<resources>
<item name="main_layout" type="layout">@layout/twopanes_narrow</item>
<bool name="has_two_panes">true</bool>
</resources>
順帶留意那個 has_two_panes 布林值——它稍後會在程式碼裡派上用場。
支援多尺寸意味著圖片也得能伸縮。若直接在可縮放的元件上使用普通圖片,系統會平均拉伸每個像素,邊框與圖示很快就變形。正解是 .9 圖:一種特殊格式的 PNG,用來標明哪些區域可拉伸、哪些不可。
製作方式很簡單:在圖片四周各加 1px 的透明邊界,然後用黑線標記。左上邊的黑線代表拉伸區域,右下邊的黑線代表 padding(內容與邊緣的間距)。
先來看右下邊的意義。兩張圖的差别只在右下邊的黑線:
上圖右下邊標了兩段,形成四向 padding,所以內容(深藍區域)被擠到正中央;下圖右下邊的黑線貫穿整個長度,等於沒有 padding,內容便填滿整張圖。
這也解釋了下面這個現象:同樣用 wrap_content,圖一卻比圖二大一圈。
差別就在 padding。若替圖一明確加上 padding=0,覆寫掉圖片自帶的內距,兩者就一樣大了:
再來看左上邊的拉伸區域。下面兩張只設了上下的線:
上圖的黑線只覆蓋純色區域,拉伸時圖示不受影響;下圖的拉伸區把圖示包了進去,一拉伸圖示就變形。紅線處就是系統給的警告提示,提醒你這樣標記會導致不理想的效果。
相同數量的像素在不同密度螢幕上的實體尺寸不同,所以用 px 描述版面必然出問題。請務必用 dp 指定間距與尺寸,用 sp 指定字級——sp 會回應使用者的字型大小偏好,對視力不便的使用者尤其重要。
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/clickme"
android:layout_marginTop="20dp" />
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp" />
Google 建議用 dp 取代 px,但這並未徹底消滅問題。舉個情境:以 Nexus 5 為測試機,總寬 360dp,水平放兩個按鈕——一個 150dp 靠左、一個 200dp 靠右、間隔 10dp,看起來剛剛好。

換到 Nexus S 或 Nexus One 上執行:

兩個按鈕重疊了。明明已經用了 dp,為什麼還會這樣?
因為 dp 只解決了「密度」差異,卻沒解決「螢幕可用寬度」差異。各機型的 dp 寬度並不相同:Nexus S / One 是 hdpi、寬 320dp;Nexus 5 是 xxhdpi、寬 360dp;Galaxy Nexus 是 xhdpi、寬 384dp;Nexus 6 是 xxxhdpi、寬 410dp。光是 Google 自家產品就橫跨 320dp 到 410dp,整整 90dp 的差距,而且寬度與密度之間並無固定關聯。

所以務實的做法是:盡量用 match_parent 與 wrap_content,少用固定 dp 寫死長寬,再搭配 weight 分配比例。多數情況這樣就夠了。
如果追求更徹底的一致性,還有個思路(來自 Android Day Day Up 社群【blue-深圳】的分享):既然 px 因密度而異、dp 因寬度而異,那乾脆自訂一套單位——把螢幕寬度固定切成 320 份、高度固定切成 480 份,再按各解析度的實際像素換算成 dimen 值。
用一支小程式批量產生這些 values 檔案即可:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
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(800, 1280);
makeString(1080, 1812);
makeString(1080, 1920);
makeString(1440, 2560);
}
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;
}
}
以 320×480 來說,份數與像素剛好一比一,所以 x1 = 1px:
<?xml version="1.0" encoding="utf-8"?> <resources> <dimen name="x1">1.0px</dimen> <dimen name="x2">2.0px</dimen> <dimen name="x3">3.0px</dimen> ... 中間省略 ... <dimen name="x318">318.0px</dimen> <dimen name="x319">319.0px</dimen> <dimen name="x320">320px</dimen> </resources>
1080×1920 呢?由於 1080 / 320 ≈ 3.37,所以 x1 = 3.37px:
<?xml version="1.0" encoding="utf-8"?> <resources> <dimen name="x1">3.37px</dimen> <dimen name="x2">6.75px</dimen> <dimen name="x3">10.12px</dimen> ... 中間省略 ... <dimen name="x319">1076.62px</dimen> <dimen name="x320">1080px</dimen> </resources>
無論哪種解析度,x320 永遠代表螢幕寬、y480 永遠代表螢幕高。
使用方式:把產生的各組 values 資料夾丟進 res 目錄,拿到設計稿後,以某個基準解析度換算出的像素數去引用對應的 dimen 名稱即可。這樣一来,不論裝置寬度是 320dp、360dp 還是 410dp,都能完美對齊。

但圖中仍有三台沒適配——因為生成的 values 裡沒有對應的解析度。這也點出了方案的兩個明顯代價:一是必須盡可能涵蓋所有解析度,缺一個就可能嚴重走形甚至出錯;二是這麼多檔案會讓 APK 體積與維護成本同步上升。而且本質上它用的仍是 px,與 Google 的建議方向相左,未來系統行為若調整,可能出現難以預期的問題。因此這個方案要審慎評估、按專案取捨。
Android 會跑在各種密度的裝置上,所以圖片資源應該覆蓋低、中、高、超高密度。做法是先取得向量原始檔,再依倍率輸出:
也就是說,若 xhdpi 版本是 200×200px,那 hdpi / mdpi / ldpi 就分別輸出 150×150、100×100、75×75。放進 res 下對應的 mdpi、hdpi、xhdpi、xxhdpi 目錄,系統會依裝置密度自動挑選。之後只要寫 @drawable/id,取用的永遠是合適的那張。
要注意的是:.9 圖或不需要多版本的圖片,直接放 drawable/ 即可;多版本圖片則一定要放對資料夾,否則會被錯誤縮放而出現模糊或變形。
版面能自動切換之後,互動流程也得跟著調整。雙面板模式下點左側項目,內容直接在右側展開;單面板模式下同樣的操作,則應該跳到另一個 Activity。
最可靠的方式不是寫死螢幕尺寸判斷,而是「看某個 View 存不存在、可不可見」:
public class NewsReaderActivity extends FragmentActivity {
boolean mIsDualPane;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
View articleView = findViewById(R.id.article);
mIsDualPane = articleView != null &&
articleView.getVisibility() == View.VISIBLE;
}
}
這種寫法的彈性遠勝於針對具體配置的硬編碼判斷。同一個技巧也能用來處理「元件可能不存在」的情況——例如某個只在舊版系統才有的按鈕:
Button catButton = (Button) findViewById(R.id.categorybutton);
OnClickListener listener = /* create your listener here */;
if (catButton != null) {
catButton.setOnClickListener(listener);
}
@Override
public void onHeadlineSelected(int index) {
mArtIndex = index;
if (mIsDualPane) {
/* 雙面板:在右側顯示報導 */
mArticleFragment.displayArticle(mCurrentCat.getArticle(index));
} else {
/* 單面板:另開一個 Activity */
Intent intent = new Intent(this, ArticleActivity.class);
intent.putExtra("catIndex", mCatIndex);
intent.putExtra("artIndex", index);
startActivity(intent);
}
}
同理,導覽列的呈現方式也該依版面調整:雙面板用 tab,單面板用下拉選單。
final String CATEGORIES[] = { "熱門報道", "政治", "經濟", "Technology" };
public void onCreate(Bundle savedInstanceState) {
....
if (mIsDualPane) {
/* 使用分頁做導覽 */
actionBar.setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_TABS);
int i;
for (i = 0; i < CATEGORIES.length; i++) {
actionBar.addTab(actionBar.newTab().setText(
CATEGORIES[i]).setTabListener(handler));
}
actionBar.setSelectedNavigationItem(selTab);
} else {
/* 使用下拉式清單(spinner) */
actionBar.setNavigationMode(android.app.ActionBar.NAVIGATION_MODE_LIST);
SpinnerAdapter adap = new ArrayAdapter(this,
R.layout.headline_item, CATEGORIES);
actionBar.setListNavigationCallbacks(adap, handler);
}
}
多螢幕設計中常見的模式是:同一段介面在大螢幕上作為面板,在小螢幕上則獨立成一個 Activity。與其複製兩份程式碼,不如重用同一個 Fragment 子類。
雙面板配置中使用了 ArticleFragment:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<fragment android:id="@+id/headlines"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.HeadlinesFragment"
android:layout_width="400dp"
android:layout_marginRight="10dp"/>
<fragment android:id="@+id/article"
android:layout_height="fill_parent"
android:name="com.example.android.newsreader.ArticleFragment"
android:layout_width="fill_parent" />
</LinearLayout>
小螢幕的 Activity 則用程式碼掛上同一個 Fragment:
ArticleFragment frag = new ArticleFragment(); getSupportFragmentManager().beginTransaction().add(android.R.id.content, frag).commit();
效果等同於在 XML 中宣告,但在這個案例中更合適——因為報導片段是該 Activity 唯一的元件。
設計 Fragment 時有一個關鍵原則:不要與特定 Activity 強耦合。做法是定義一個介面概括所需的互動方式,讓宿主 Activity 去實作:
public class HeadlinesFragment extends ListFragment {
...
OnHeadlineSelectedListener mHeadlineSelectedListener = null;
/* 必須由宿主 Activity 實作 */
public interface OnHeadlineSelectedListener {
public void onHeadlineSelected(int index);
}
...
public void setOnHeadlineSelectedListener(OnHeadlineSelectedListener listener) {
mHeadlineSelectedListener = listener;
}
}
使用者點選標題時,片段只通知那個介面,而非硬綁某個具體 Activity:
public class HeadlinesFragment extends ListFragment {
...
@Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
if (null != mHeadlineSelectedListener) {
mHeadlineSelectedListener.onHeadlineSelected(position);
}
}
...
}
若元件間的溝通更複雜,也可以引入類似 EventBus 這類「發布—訂閱」機制的第三方框架,進一步降低耦合。
以 7 吋平板為例:縱向時用獨立 Activity 顯示報導,橫向時改用雙面板。使用者正在閱讀時若旋轉螢幕,就必須妥善收尾:
public class ArticleActivity extends FragmentActivity {
int mCatIndex, mArtIndex;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCatIndex = getIntent().getExtras().getInt("catIndex", 0);
mArtIndex = getIntent().getExtras().getInt("artIndex", 0);
// 若現在該用雙面板模式,就結束自己回到主 Activity
if (getResources().getBoolean(R.bool.has_two_panes)) {
finish();
return;
}
...
}
}
這裡就用上了前面在 values-*/layouts.xml 中定義的 has_two_panes——版面判斷與業務邏輯就此打通。
官方給過兩種思路:一是以 mdpi 為基準設計再放大,二是直接以高解析度設計再按比例縮小。實務上強烈建議用第二種,因為小圖放大會產生像素流失、細節糊掉,這個損失幾乎無法補救。基準解析度可以選 1280×720 或 1920×1080。
不同的 ScaleType 適配表現差很多。多數情況下,centerCrop 能取得較穩定的視覺效果;若圖片必須完整呈現,則可考慮 fitCenter 並搭配合適的背景色。
有些數值無法在 XML 中靜態決定,例如 PopupWindow 的顯示位置與偏移量。這時就動態取得螢幕參數再計算:
public class ScreenSizeUtil {
public static int getScreenWidth(Activity activity) {
return activity.getWindowManager().getDefaultDisplay().getWidth();
}
public static int getScreenHeight(Activity activity) {
return activity.getWindowManager().getDefaultDisplay().getHeight();
}
}
補充一個實務提醒:getWidth() 與 getHeight() 在 API 13 之後已被標記為 deprecated,新專案請改用 WindowManager.getCurrentWindowMetrics() 或 DisplayMetrics,並留意狀態列、導覽列與劉海(cutout)造成的可用區域差異。
回顧一下這條路:先搞懂尺寸、解析度、密度的關係,理解 dp 為何是預設答案、又為何不足夠;接著用 match_parent / wrap_content / weight 建立彈性骨架,用 RelativeLayout 描述元件關係,用限定符與別名處理平板與方向差異,用 .9 圖與多密度圖片解決資源縮放;最後讓 UI 流程依實際版面做出不同反應。
沒有任何單一方案能一次解決所有問題,適配本質上是「用合理的成本換取足夠好的體驗」。把主流解析度顧好、把彈性配置寫對、把備用版面準備齊,多數專案都能拿到令人滿意的結果。
更多延伸閱讀可參考鴻洋的〈Android 螢幕適配方案〉。
2015 年 Android 作品集回顧
2015 年 Android 作品集回顧 回顧 2015 年,這段時間累積了幾個 Android 專案經驗。從新聞閱讀、知識內容到寵物醫療服務,每個產品都讓人重新理解開發
用 Android Studio 運行 NDK 程式的完整步驟
用 Android Studio 運行 NDK 程式的完整步驟 最近打算研究 Android 雙進程守護,由於過去用 Eclipse 寫 JNI 習慣了,如今主要改用 A
PhotoView 圖片縮放實作:搭配 ViewPager 打造流暢的圖片瀏覽體驗
圖片的放大縮小效果,這裡採用 GitHub 上的開源專案 PhotoView 來實作。專案網址:https://github.com/chrisbanes/PhotoV
解決 Android Studio 報錯:9-patch 圖片 malformed 問題
搞定 Android Studio 的 9-patch 圖片錯誤 在 Android Studio 開發時,如果 .9.png 圖片製作不規範,就可能出現 9-patch