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

Android 資源檔的引用方式:XML 與系統資源

編輯:關於 Android 程式設計

把字串、顏色、尺寸抽到資源檔而不是寫死在程式碼或版面裡,是 Android 開發的基本紀律。好處很直接:換語言只要多一份 values-xx,換主題只要改一個顏色值,不必動任何邏輯。本文整理兩種最常見的引用場景。

一、在 XML 之間互相引用

統一格式如下:

 attribute="@[packagename:]resourcetype/resourceidentifier" 

拆解一下這串格式:

  • packagename 可省略。省略時指目前 App 的資源,寫出來則可跨 App 引用別人的資源。
  • resourcetype 是資源種類,常見的有 string、color、dimen、drawable、layout、style。
  • resourceidentifier 就是你在 values 檔案中設定的 name。

以下面這段版面為例,同時引用了 strings.xml、color.xml、dimen.xml 三個檔案中的值:

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:padding="@dimen/standard_border">

  <EditText
    android:id="@+id/myEditText"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/stop_message"
    android:textColor="@color/opaque_blue" />
</LinearLayout> 

對應的 values 檔案大致長這樣:

 <!-- res/values/strings.xml -->
<resources>
  <string name="stop_message">再按一次就會離開應用程式</string>
</resources>

<!-- res/values/colors.xml -->
<resources>
  <color name="opaque_blue">#3366CC</color>
</resources>

<!-- res/values/dimens.xml -->
<resources>
  <dimen name="standard_border">8dip</dimen>
</resources> 

二、引用系統內建的資源

Android 自己也準備了一大批預設的字串、顏色與尺寸,可以直接拿來用,不必重複造輪子。寫法是在型別前加上 android: 前綴:

在程式碼中:

 CharSequence httpError = getString(android.R.string.httpErrorBadUrl); 

在 XML 中:

 <EditText
  android:id="@+id/myEditText"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="@android:string/httpErrorBadUrl"
  android:textColor="@android:color/darker_gray" /> 

關鍵差異就在那個 android 前綴:有它代表向系統要資源,沒它代表向自己的專案要資源。少寫這個前綴是編譯期常見錯誤的來源。

幾個實務上的建議

  • 字串一律進 strings.xml。寫死在版面或程式碼中的中文,會讓多語支援變成惡夢。
  • 帶參數的字串用位置標記。例如 <string name="count_fmt">共有 %1$d 筆資料</string>,取值時用 getString(R.string.count_fmt, 10)。用 %1$d 而非 %d,是因為不同語言的語序可能不同。
  • 顏色與尺寸集中管理。把主色、間距定義成語意化的名稱(如 colorPrimary、spacing_normal),換設計稿時只改一處。
  • resource qualifier 是資源系統最強的地方。values-night(深色模式)、values-land(橫向)、values-zh-rTW(繁中)、values-xhdpi(螢幕密度)等,系統會自動挑選最合適的一份,完全不需要你寫 if。
  • 別過度依賴系統資源。系統的顏色與尺寸在不同版本間可能被調整,若對視覺有精準要求,還是自己定義比較安全。

一句話總結:自己的資源用 @type/name,系統的資源用 @android:type/name。把這個規則記牢,並養成「寫死之前先想能不能抽成資源」的習慣,專案的可維護性會明顯不同。

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