2

The following code shows how to set the background color of a button in API 23. How can I get the similar functionality in former APIs?

Button aButton = (Button) findViewById(R.id.aButton);
aButton.setBackgroundColor(getResources().getColor(R.color.aColor));
ashubuntu
  • 747
  • 7
  • 20
  • What part of it won't work below API 23? – Karakuri Dec 07 '15 at 00:32
  • I have set my minSdk to 15 and when I write this code, the android studio code analyzer warns me of this saying something like **API 23 is needed to run this code, your minimum Sdk level is API 15**. From this warning message, I have been concerned. – ashubuntu Dec 07 '15 at 01:57
  • Does it say what specifically is API 23 and above? Everything I see in the code you posted is available on API 15. – Karakuri Dec 07 '15 at 05:12
  • You're right about the code above. First, I wrote **public int getColor(int id) throws NotFoundException** and changed my mind after getting the notification that it was deprecated. So I used **public int getColor(int id, Resources.Theme theme) throws NotFoundException** to get over that warning. But it says **Call requires API level 23 (current min is 15): android.content.res.Resources#getColor** and suggests me to add this annotation **@TargetApi(Build.VERSION_CODES.M)**. I suspect that the up-to-date function wont execute in a device run on an older OS that is based upon an API below 23. – ashubuntu Dec 07 '15 at 09:13
  • So if I use the function **public int getColor(int id, Resources.Theme theme) throws NotFoundException** and the annotation **@TargetApi(Build.VERSION_CODES.M)**, will it cause a problem in the APIs lower than level 23? – ashubuntu Dec 07 '15 at 15:04

1 Answers1

2

Use ContextCompat.getColor(context, R.color.aColor). ContextCompat is part of the support library.

See this answer for more details.

Community
  • 1
  • 1
Karakuri
  • 38,365
  • 12
  • 84
  • 104