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

別急著自己做資源:Android 系統資源 reuse 完整指南

編輯:關於 Android 程式設計

一個頁面上往往會用到大量控制項,控制項又要吃不少資源。其實 Android 系統本身已經備妥各種字串、圖片、動畫、樣式與版面配置,都可以在應用中直接取用。

善用系統資源有三重好處:減少記憶體佔用、省下重複工時,還能縮小安裝包體積。

一、使用系統定義的 id

一般的 ListView 寫法:

<ListView
    android:id="@+id/mylist"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"/>

若沒有特別需求,可以直接沿用系統的 id:

<ListView
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"/>

在 XML 中引用系統 id,只要加上 @android: 前綴。在 Java 程式碼中用法與自己的資源幾乎一樣,唯一差別是要用 android.R 而非應用自身的 R 類別——取得這個 ListView 就是 android.R.id.list。

二、使用系統的圖片資源

假設應用定義了一個選單:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="https://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/menu_attachment"
        android:title="附件"
        android:icon="@android:drawable/ic_menu_attachment" />
</menu>

這裡本想引用系統內建的「附件」圖示,但 Build 之後出現錯誤:

error: Error: Resource is not public.
(at 'icon' with value '@android:drawable/ic_menu_attachment').

從訊息看得出來:這個資源沒有對外公開,所以無法直接引用。

解法很直接:到 Android SDK 裡找到對應的圖片檔,複製到自己的專案目錄,再用 android:icon="@drawable/ic_menu_attachment" 引用。

這樣做有兩個好處:美工不必重畫一份既有的圖,省下可觀工時;同時應用的視覺風格能與系統保持一致。

另一條路:改用 @*android

除了複製資源,還可以把 @android 改成 @*android 來繞過公開限制:

android:icon="@*android:drawable/ic_menu_attachment"

改完再 Build 就不會報錯。不過要留意,@*android 屬於非公開介面,不同系統版本之間沒有相容性承諾,改版後可能失效。若應用要長期維護並上架,複製一份到自己專案裡是更穩妥的選擇。

三、使用系統的字串資源

要做一個帶「確定」與「取消」的 Dialog,可以直接用系統字串:

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <Button
        android:id="@+id/yes"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1.0"
        android:text="@android:string/yes"/>
    <Button
        android:id="@+id/no"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1.0"
        android:text="@android:string/no"/>
</LinearLayout>

用系統字串的附加價值在於多語系已經幫你做好了:@android:string/yes 與 @android:string/no 在中文環境顯示「確定」與「取消」,在英文環境則顯示「OK」與「Cancel」,不必自己維護各語系翻譯。

四、使用系統的 Style

若版面配置中有一個 TextView 用來顯示視窗標題、字體中等大小:

<TextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium" />

這裡的 android:textAppearance="?android:attr/textAppearanceMedium" 就是在用系統 style。

要特別注意前綴:使用系統 style 時要寫 ?android:,而不是 @android:。前者是主題屬性參照,會隨更換主題而變;後者是直接的資源參照。兩者混用是常見錯誤來源。

五、使用系統的顏色定義

除了上述各類,系統也定義了不少顏色。最常用的是透明色:

android:background="@android:color/transparent"

心得

Android 系統內建的資源比多數人想像的多得多,都可以在應用中直接取用。想確認有哪些可用,可以進到 $android-sdk$\platforms\android-8\data\res 底下瀏覽,系統資源一覽無遺。

值得花點時間熟悉這些資源,特別是圖片與各種 Style。開發時能想到「這個系統可能已經有了」,往往就省下一整天的工。

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