public void listRawResources() {
Field[] fields = R.raw.class.getDeclaredFields();
for (Field field : fields) {
try {
int resId = field.getInt(null); // static field, object 參數為 null
String resName = field.getName();
Log.d("RAW_RES", "Name: " + resName + ", ID: 0x" + Integer.toHexString(resId));
// 使用資源
// InputStream is = getResources().openRawResource(resId);
} catch (IllegalAccessException e) {
Log.e("RAW_RES", "Access failed: " + field.getName(), e);
}
}
}
R.xxx.class.getDeclaredFields() 獲取所有靜態字段(資源 ID)。field.getInt(null) 讀取靜態 int 值,傳 null 而非實例。R.drawable、R.string、R.layout 等內部類。
D/RAW_RES: Name: song, ID: 0x7f040000
D/RAW_RES: Name: background_music, ID: 0x7f040001
| 需求 | 正規做法 |
|---|---|
| 動態播放多個 raw 音頻 | 將檔名存入 assets/playlist.json 或 res/values/arrays.xml,讀取名稱後 getResources().getIdentifier(name, "raw", getPackageName()) 獲取 ID |
| 批量加載 drawable | 命名規律(如 img_01...img_20)循環 getIdentifier,或使用 TypedArray 定義 <array name="imgs"><item>@drawable/img_01</item>...</array> |
| 運行時列出所有資源 | 極少見真實需求,若確需,構建期腳本生成索引文件打包進 assets |
反射遍歷 R 類技術上可行,但屬於「技術債」,生產環境嚴禁使用。善用 getIdentifier、TypedArray、資產文件索引等正規機制,保證構建穩定與可維護性。