android.content.res.Resources$NotFoundException: Resource ID #0xff412804
問題原因
-
該異常表示 Android 系統嘗試通過資源 ID 查找資源,例如,顏色、圖片等,但未查找到對應資源
-
其中,
0xff412804
是一個硬編碼的整型顏色值,不是有效的資源 ID
問題復現
- 調用
setBackgroundResource(int resid)
方法時,傳入了一個錯誤的資源 ID(顏色值)
TextView tvContent = findViewById(R.id.tv_content);tvContent.setBackgroundResource(0xff412804);
- 調用
getColor(@NonNull Context context, @ColorRes int id)
方法時,傳入了一個錯誤的資源 ID(顏色值)
int color = ContextCompat.getColor(this, 0xff412804);
- 調用
getDrawable(int id)
方法時,傳入了一個錯誤的資源 ID(顏色值)
Drawable drawable = getResources().getDrawable(0xff412804);
處理策略
- 注意避免顏色值與混淆 ID 資源,直接將顏色值作為資源 ID 傳遞
- 對于顏色,可以直接設置顏色值
// 設置背景顏色TextView tvContent = findViewById(R.id.tv_content);tvContent.setBackgroundColor(0xff412804);
// 設置文本顏色TextView tvContent = findViewById(R.id.tv_content);tvContent.setTextColor(0xffff0000);
- 加載顏色資源
Drawable drawable = new ColorDrawable(0xff412804);