【发布时间】:2017-03-23 19:38:15
【问题描述】:
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); 来改变颜色??
【问题讨论】:
-
当您碰巧想要从资源中设置颜色时,其他开发人员可能想要在 Java 中硬编码颜色,或者从文件/数据库中加载颜色,或者获取颜色作为一部分Web 服务响应,或随机选择一种颜色。因此,
setBackgroundColor()采用 color,而不仅仅是颜色的资源 ID。
标签: android converter getcolor