简体   繁体   中英

How to call colors in resources dynamically in Android?

I am trying to use colors created in my res/values/colors.xml file. But when I make the call dynamically the program doesn't compile and instead recommends: Should pass resolved color instead of a resource id.

Color Code:

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

Activity Code:

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);

Change the code to the following:

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM