90

I have used context.getDrawable() like this in my project:

Drawable greenProgressbar = context.getDrawable(R.drawable.custom_progressbargreen);

But Eclipse is giving me an error that it needs a Minimum API level of 21. This would mean after a quick google search my APP will only be usable on Android 5.0. Since not all devices are using this version of android I would like to have an alternative for context.getDrawable().

9 Answers 9

207

The previously accepted method has been deprecated, according to the SDK 22 documentation:

Prior to android.os.Build.VERSION_CODES#JELLY_BEAN, this function would not correctly retrieve the final configuration density when the resource ID passed here is an alias to another Drawable resource. This means that if the density configuration of the alias resource is different than the actual resource, the density of the returned Drawable would be incorrect, resulting in bad scaling.

As pointed out in this answer better solution would be to use ContextCompat: ContextCompat.getDrawable(context, R.drawable.***)

1
  • 1
    I accepted this answer now as it is more relevant :)
    – Bram
    Commented Nov 5, 2015 at 10:56
26

Add a getResources() after the context:

Drawable greenProgressbar = context.getResources().getDrawable(R.drawable.custom_progressbargreen);
1
  • 4
    Resources.getDrawable was deprecated in favor of Context.getDrawable Commented Dec 7, 2015 at 23:36
12

I had a same situation which I wanted to reference getDrawable() method which is now deprecated.

What I used:

myButton.setImageDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.ic_btn_off));
9
Drawable greenProgressbar = context.getResources().getDrawable(R.drawable.custom_progressbargreen);
1
  • This is deprecated. Commented Aug 20, 2020 at 0:17
2

You can also set the resource directly without working with the drawable (Kotlin):

btn.setImageResource(R.drawable.ic_XXX)
2

Solution for Kotlin programmers looks like:

val greenProgressbar = context!!.getDrawable(R.drawable.custom_progressbargreen)

or (from API 22)

val greenProgressbar = ContextCompat.getDrawable(R.drawable.custom_progressbargreen)
2
AppCompatResources.getDrawable(context, R.drawable.*)
1

You should use " getDrawable(id, this.getTheme()) ". This method is not deprecated till now.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    view.setBackground(getResources().getDrawable(R.drawable.radioline,this.getTheme()));
} else {
   view.setBackground(getResources().getDrawable(R.drawable.radioline));
}
1

I agree using ContextCompact.getDrawable(Context context, int resID). It worked for me and my app targets API 19.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.