首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 動態獲取 Drawable 資源 ID:getResources().getIdentifier()

     編輯:程式設計綜合問答

需求

圖片資源命名規則 d002_p001 ~ d002_p050,需動態構建陣列而非手寫 50 個常數。

代碼實現

int[] images = new int[50];
for (int i = 0; i < 50; i++) {
    String resName = String.format("d002_p%03d", i + 1); // d002_p001, d002_p002...
    int resId = getResources().getIdentifier(resName, "drawable", getPackageName());
    if (resId != 0) {
        images[i] = resId;
    } else {
        Log.w("RES", "Missing: " + resName);
    }
}

關鍵點

  • getIdentifier(name, "drawable", packageName) 回傳 0 表示資源不存在
  • 命名需與 res/drawable/ 下檔名一致(不含副檔名)
  • 效能:啟動時一次性構建陣列緩存,避免頻繁呼叫 getIdentifier

Kotlin 版本

val images = (1..50).map { 
    resources.getIdentifier("d002_p%03d".format(it), "drawable", packageName) 
}.filter { it != 0 }.toIntArray()

替代方案

  • 將圖片放入 assets/ 目錄,用 AssetManager.open() 讀取,無需資源 ID
  • 使用 RecyclerView + Glide 直接用字串路徑載入
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved