textView.setBackgroundColor(R.color.white); // 錯誤:傳入資源 ID,非顏色值
textView.setTextColor(R.color.solid_red); // 同理錯誤
textView.setBackgroundColor(ContextCompat.getColor(context, R.color.white));
textView.setTextColor(ContextCompat.getColor(context, R.color.solid_red));
setBackgroundColor(int color) 參數是顏色值(如 0xFFFFFFFF),而 R.color.xxx 是資源索引整數(如 0x7f060001),兩者含義完全不同。ContextCompat.getColor 內部調用 Resources.getColor,正確解析顏色資源並兼容舊版 API。<TextView
android:background="@color/white"
android:textColor="@color/solid_red" />
XML 會自動解析資源引用,無需手動獲取。