解释使用 ContextCompat class 中的 getColor() 方法的主要原因?

explain the main reason to use getColor() method from ContextCompat class?

LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear);
int color = ContextCompat.getColor(getContext(), mColorResourceId);
linearLayout.setBackgroundColor(color);

我有这行代码: mColorResourceId 保持 R.color.category_numbers -> mColorResourceId = R.color.category_numbers

当我将 mColorResourceId 直接传递给 setBackgroundColor(mColorResourceId); 时,尽管方法接受了 int 值,但它并没有改变颜色。

我的问题是为什么我需要这个额外的步骤 int color = ContextCompat.getColor(getContext(), mColorResourceId); 来更改颜色??

setBackgroundColor() 方法接受一个 int,它应该是 aarrggbb 格式的颜色值。资源IDR.color.category_numbers也是一个int,但不是颜色值;相反,它是 color 资源的标识符。调用 ContextCompat.getColor(getContext(), mColorResourceId) 检索对应于 mColorResourceId.

的实际颜色值

Android 进行这种间接访问的部分原因是为了提供灵活性。返回的实际颜色可能取决于当前主题或设备配置,并且可能会在 运行 时间实际发生变化(取决于您声明颜色资源的方式)。