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

Android 值資源完全解析:從 strings.xml 到自定義屬性

編輯:關於 Android 程式設計

值資源是 Android 應用不可或缺的組成部分,負責承載 UI 設定與文字顯示。常見類型包含字串、字串陣列、整數、整數陣列、尺寸、布林、屬性、顏色、風格、主題與標識符等。

這類資源存放於 res/values,英文為預設目錄,簡體中文為 res/values-zh-rCN,繁體中文為 res/values-zh-rTW。命名遵循 ISO 639-2 語言碼與 ISO 3166 區域碼規範,格式為 values-<語言>-<地區>。

一、字串資源

1. 定義方式

字串是最常用的值資源,通常寫在 res/values/strings.xml:

<resources>
    <string name="edit_event_from_label">From</string>
    <string name="edit_event_all_day_label">All day</string>
</resources>

若某個字串不需要本地化,應把 translatable 屬性設為 false:

<!-- 不需翻譯 -->
<string name="voice_mode_off" translatable="false">2</string>

除 name 之外,另一個值得注意的屬性是 msgid,它通常用於框架層,應用層一般不需顯式宣告。

另外,某些符號(例如 Noto 字型中的 &prime;)無法直接寫進字串資源,必須以轉義字元呈現。

資源載入是以資源 ID 為線索進行的,Android 不允許在同一命名空間中出現重複的 ID。

2. 引用字串資源

Android 的資源分為系統資源與應用資源,兩者引用方式略有差異。並非所有系統資源都對應用層開放,開放的部分定義在 frameworks/base/core/res/res/values/public.xml。未開放的系統資源可這樣載入:

getString(com.android.internal.R.string.xxx);
// 在 XML 中則用 "@com.android.internal.R.string/..." 形式

其他類型系統資源的載入方式與字串類似,後文不再重複說明。

(1)引用應用自身的字串

在 XML 配置檔中:

<EditText
    android:id="@+id/text"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="@string/hello_activity_text_text"
    android:textSize="18sp" />

在 Java 檔案中:

// 採用 "R.string.xxx" 方式
test.setText(R.string.hello_activity_text_text);

(2)引用框架層的字串

在 XML 配置檔中:

<EditText
    android:id="@+id/text"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="@android:string/cancel"
    android:textAppearance="?android:attr/textAppearanceMedium" />

在 Java 檔案中:

// 採用 "android.R.string.xxx" 方式
test.setText(android.R.string.cancel);

3. 資料交換與進階用法

面對較複雜的字串資料,Android 支援 XLIFF(XML Localization Interchange File Format)與通配符,便於翻譯流程銜接。

通配符:單一字串標籤中僅支援一個通配符。

<string name="test">test "%1"</string>

Java 端的載入寫法:

test.setText(getString(R.string.hello).replace("%1", String.valueOf(curPage)));

XLIFF:以 ANR 提示為例,字串資源寫成:

<string name="anr_process">Process <xliff:g id="process">%1$s</xliff:g> is not responding.</string>

其命名空間宣告為 xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"。Java 端使用帶參數的取字串方法:

// getString(resId, formatArgs)
res.getString(com.android.internal.R.string.anr_process,
        name1.toString(), name2.toString());

加上底線:Android 原生的文字特效目前主要支援粗體與斜體,若要底線效果,需借助 HTML 語法:

textView.setText(Html.fromHtml("<u>" + helloStr + "</u>"));

切換語言:語言切換是透過資源管理器完成的:

Resources resources = getResources();
Configuration config = resources.getConfiguration();
DisplayMetrics dm = resources.getDisplayMetrics();
config.locale = Locale.SIMPLIFIED_CHINESE;
resources.updateConfiguration(config, dm);

用類似手法也能切換螢幕密度、MCC、MNC、螢幕方向等,不過部分設定可能需要較高層級的權限。

二、字串陣列

1. 定義

字串陣列常用於下拉選單等場景。若不希望它隨語言環境變化,可把 translatable 設為 false:

<string-array name="preferences_alert_type_values" translatable="false">
    <item>"0"</item>
    <item>"1"</item>
    <item>"2"</item>
</string-array>

2. 載入

在 XML 中:

<ListPreference
    android:entries="@array/preferences_alert_type_labels"
    android:entryValues="@array/preferences_alert_type_values"
    android:key="preferences_alerts_type"
    android:title="@string/preferences_alerts_type_title" />

在 Java 中:

ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
        this, R.array.colors, android.R.layout.simple_spinner_item);
// 採用 "R.array.xxx" 方式

三、整數陣列

用法與字串陣列幾乎一致:

<integer-array name="config_virtualKeyVibePattern">
    <item>0</item>
    <item>10</item>
    <item>20</item>
    <item>30</item>
</integer-array>

Java 端載入:

int[] tmpArray = getResources().getIntArray(
        com.android.internal.R.array.config_virtualKeyVibePattern);

四、其他簡單值:布林與整數

這類資源在應用開發中不算高頻,常用於承放應用設定項:

<resources>
    <bool name="config_sf_limitedAlpha">false</bool>
    <integer name="config_shortAnimTime">150</integer>
</resources>

Java 端載入:

mLimitedAlphaCompositing = context.getResources().getBoolean(
        com.android.internal.R.bool.config_sf_limitedAlpha);
// 採用 "R.bool.xxx" 方式

五、尺寸資源

<dimen name="thumbnail_width">84dp</dimen>
<dimen name="thumbnail_height">63dp</dimen>

Java 端載入:

int w = getResources().getDimensionPixelSize(
        com.android.internal.R.dimen.thumbnail_width);

六、屬性資源(attrs)

屬性檔通常放在 res/values/attrs.xml,由 declare-styleable、eat-comment、attr 等標籤組成。

declare-styleable 用於宣告一組屬性,一組可包含多個屬性:

<declare-styleable name="Animation">
    ...
</declare-styleable>

eat-comment 用於標示其後內容為註解。attr 則用於宣告單一屬性,包含屬性名與屬性格式兩部分。

Android 常見的屬性格式:

  • reference:對資源的引用
  • color:顏色
  • dimension:尺寸
  • string:字串
  • boolean:布林值
  • integer、float、fraction 等數值型別

Android 允許同一屬性支援多種格式。以 background 為例,它既能載入配置檔,也能直接接受 ARGB 值。

為屬性設定偏好值有 enum 與 flag 兩種作法,其中 flag 以位元方式表示:

<attr name="inputType">
    <enum name="normal" value="0" />
    <enum name="spannable" value="1" />
    <enum name="editable" value="2" />
</attr>

Java 端載入自定義屬性:

TypedArray a = context.obtainStyledAttributes(attrs,
        com.android.internal.R.styleable.Animation);
...
a.recycle();   // 用後回收,供後續複用

七、顏色資源

顏色定義多放在框架層的資源目錄中。在應用層引用顏色屬性而非到處硬寫色值,有助於在系統層面維持 UI 一致性。宣告格式為 ARGB:

<resources>
    <color name="magic_flame">#00ffffff</color>
    <color name="button_text">#ffffffff</color>
</resources>

XML 中引用:

<TextView
    android:id="@+id/error"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/red"
    android:visibility="gone" />

Java 中引用:

// 採用 "R.color.xxx" 方式
setBackgroundColor(getResources().getColor(R.color.candidate_background));

Google 也提供了大量系統顏色,如 primary_text_dark、primary_text_light、white、black、transparent 等,可直接取用。

八、風格與主題

一個好的應用除了程式碼層面要具備可讀性、可擴充性、複用性與效能,使用者體驗同樣關鍵,而風格設計直接決定了文字與圖片的視覺呈現。

<resources>
    <style name="digit_button_style" parent="button_style">
        <item name="android:background">@drawable/blue_button</item>
    </style>
</resources>

套用方式(XML):

<com.android.calculator2.ColorButton
    android:id="@+id/digit7"
    style="@style/digit_button_style"
    android:text="@string/digit7" />

主題在框架層更為常用。對於進行差異化的廠商而言,維持一致的主題是基本的 UI 需求;定義統一風格檔供全公司產品引用是很實際的做法:

<style name="Theme.Light.NoTitleBar">
    <item name="android:windowNoTitle">true</item>
</style>

風格與主題的設計看似簡單,實際牽涉的維度很多:既要照顧使用者的視覺感受,也要兼顧不同層次、不同地區使用者的文化差異。如何把資訊以統一、簡潔而優雅的方式呈現,考驗的是 UI/UE 工程師長年的累積與素養。

九、標識符資源(id)

標識符檔對應用層開發者較陌生,但並非接觸不到——使用系統提供的 ListView、Tab 等元件時就會牽涉其中。

<resources>
    <item name="background" type="id" />
    <item name="checkbox" type="id" />
    <item name="content" type="id" />
</resources>

實務上常需自定義 Tab 版面,這時必須把 tabhost、tabcontent、tabs 等控制項 ID 宣告為系統 ID:

<TabHost xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="0dip"
            android:layout_weight="1" />
    </LinearLayout>
</TabHost>

自定義清單版面時,則必須把 ListView 的 ID 宣告為系統 ID:

<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</FrameLayout>
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved