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

Android 中如何使用資源(Resource):R 類、Resources 與資源引用語法

編輯:Android 開發教學

資源的兩種來源

Android 平台可以使用本地資源,也可以使用系統資源,兩者的引用語法略有不同。

R 類與 Resources 類

Android 會自動產生一個靜態的 R 類來管理資源。R 類中包含多個靜態子類,每個子類把同一類別的資源表示為變數形式,例如 R.string、R.drawable、R.layout 等。

而資源表本身則被表示為 Resources 類的一個實例。

如圖:

使用 getResources() 方法可以取得這個實例,而每一種可用的資源類型都對應一組 getter 方法:

Resources res = getResources();
String appName = res.getString(R.string.app_name);
Drawable icon = res.getDrawable(R.drawable.ic_launcher);

資源引用語法

使用 @ 符號,就可以在一個資源中引用另一個資源。

如:

若要使用 android.R 類中提供的系統 Android 資源,則需要指定 android 作為套件名稱,也就是寫成 @android: 而不是 @。例如:

android:background="@android:color/white"
android:icon="@android:drawable/ic_menu_add"

若要使用主題樣式,則需使用 ?android: 寫法,讓樣式能隨目前主題變動:

android:textColor="?android:attr/textColorPrimary"

動態資源選擇機制

Android 支援依裝置條件自動挑選資源,例如 dpi 資源。但要使用這套機制,必須自訂資源限定符,並滿足限定符的順序規則,同時確保同一類別下的限定符具唯一性。

如圖:

常見的限定符包含 dpi、語言、螢幕尺寸、是否在夜間模式等。例如 drawable-hdpi、values-zh-rTW 分別代表高解析度圖片與繁體中文(台灣)字串資源。

運行時配置變更的處理

可以在 Activity 中(對應 activity_main 版面配置)指出要處理哪些配置變更,並在程式(MainActivity.java)中接收 Configuration 物件,以取得新的配置值:

// 程式碼中接收新的配置
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // 依 newConfig 的內容調整介面
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved