Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 依資源名稱動態取得資源 ID 的做法

編輯:Android 開發實例

做過 Android 開發的人都知道,存取程式資源基本上是靠資源 ID。這種方式既直觀,又能自動屏蔽不同解析度、語言與螢幕密度的差異,不需要在程式裡硬寫各種條件判斷。

問題出在哪裡

但有時候情境並不這麼理想。例如要根據伺服器回傳的值決定顯示哪張圖,而伺服器不可能給你一個 R.java 裡的 int 常數,最多給你一個和檔名相關的字串。資源數量少時,自己維護一份「值 → 資源 ID」的映射表還算可行;一旦數量膨脹,這種做法就難以維持。

用檔名反查資源 ID

這時透過 Resources.getIdentifier() 用名稱反查,就能省去大量維護成本。幾個簡單的範例:

Resources res = getResources();
final String packageName = getPackageName();

int imageResId = res.getIdentifier("ic_launcher", "drawable", packageName);
int imageResIdByAnotherForm = res.getIdentifier(packageName + ":drawable/ic_launcher", null, null);

int musicResId = res.getIdentifier("test", "raw", packageName);

int notFoundResId = res.getIdentifier("activity_main", "drawable", packageName);

Log.i(LOGTAG, "testGetResourceIds imageResId = " + imageResId
        + ";imageResIdByAnotherForm = " + imageResIdByAnotherForm
        + ";musicResId=" + musicResId
        + ";notFoundResId =" + notFoundResId);

執行結果

I/MainActivity( 4537): testGetResourceIds imageResId = 2130837504;imageResIdByAnotherForm = 2130837504;musicResId=2130968576;notFoundResId =0

可以看到兩種寫法得到同一個 ID,而找不到資源時會回傳 0。

API 重點整理

  • 此方法用資源名稱取得資源 ID。
  • 完整的資源名稱形式為 package:type/entry;若名稱中已完整指定,後面的 defType 與 defPackage 可以省略。
  • 省略時需明確傳入 null。
  • 官方不鼓勵使用此方法,直接用 ID 存取資源的效率更高。
  • 找不到資源時回傳 0,而 0 並不是合法的資源 ID,因此可用來做失敗判斷。
/**
 * Return a resource identifier for the given resource name.  A fully
 * qualified resource name is of the form "package:type/entry".  The first
 * two components (package and type) are optional if defType and
 * defPackage, respectively, are specified here.
 *
 * <p>Note: use of this function is discouraged.  It is much more
 * efficient to retrieve resources by identifier than by name.
 *
 * @param name The name of the desired resource.
 * @param defType Optional default resource type to find, if "type/" is
 *                not included in the name.  Can be null to require an
 *                explicit type.
 * @param defPackage Optional default package to find, if "package:" is
 *                not included in the name.  Can be null to require an
 *                explicit package.
 *
 * @return int The associated resource identifier.  Returns 0 if no such
 * resource was found.  (0 is not a valid resource ID.)
 */
public int getIdentifier(String name, String defType, String defPackage) {
    try {
        return Integer.parseInt(name);
    } catch (Exception e) {
        // Ignore
    }
    return mAssets.getResourceIdentifier(name, defType, defPackage);
}

值得注意的小細節:如果傳入的 name 本身就能被 parse 成整數,方法會直接把它當成資源 ID 回傳。

底層其實是 native 方法

上述實作最終委派給 AssetManager 的 native 方法:

/**
 * Retrieve the resource identifier for the given resource name.
 */
/*package*/ native final int getResourceIdentifier(String type,
                                                  String name,
                                                  String defPackage);

實務建議:把反查到的 ID 快取起來,避免在列表滾動或頻繁重繪的路徑上重複查詢。

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