如何在Android中动态调用资源中的颜色?

时间:2012-09-11 16:31:58

标签: android xml user-interface imageview

我正在尝试使用在res/values/colors.xml文件中创建的颜色。但是当我动态调用程序时,程序不会编译,而是建议:Should pass resolved color instead of a resource id.

颜色代码:

<?xml version="1.0" encoding="utf-8"?>
<resources>
 <color name="gold">#857500</color>
  <color name="green">#0B3B0B</color>
</resources>

活动代码:

title.setTextColor(R.color.green); 
help.setTextColor(R.color.gold);
settings.setTextColor(R.color.gold);
logout.setTextColor(R.color.gold);
profile.setTextColor(R.color.green);

1 个答案:

答案 0 :(得分:16)

将代码更改为以下内容:

title.setTextColor(getResources().getColor(R.color.green)); 
help.setTextColor(getResources().getColor(R.color.gold));
settings.setTextColor(getResources().getColor(R.color.gold));
logout.setTextColor(getResources().getColor(R.color.gold));
profile.setTextColor(getResources().getColor(R.color.green));