Android: alternative for context.getDrawable ()

I used context.getDrawable() as in my project:

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

But Eclipse tells me that it needs a Minimum API level of 21 . This would mean that after a quick Google search, my APP would only be used on Android 5.0 . Since not all devices use this version of Android, I would like to have an alternative for context.getDrawable() .

+74
java android eclipse android-drawable
Jan 06 '15 at 10:03
source share
7 answers

The previously accepted method is deprecated according to the SDK 22 documentation:

Until android.os.Build.VERSION_CODES # JELLY_BEAN, this function will not correctly retrieve the final configuration density when the resource identifier passed here is an alias of another Drawable resource. This means that if the configuration of the density of the resource of the alias is different from the actual resource, the density of the returned Drawable will be incorrect, which will lead to poor scaling.

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

+181
Aug 18 '15 at 11:37
source share

Try adding getResources() after the context so that this:

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

must work.

+24
Jan 06 '15 at 10:11
source share

I had the same situation in which I would like to refer to the getDrawable () method, which is now deprecated.

what i used

 myButton.setImageDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.ic_btn_off)); 

Hope this helps you

+9
Oct. 31 '16 at 8:38
source share

I had a similar problem. Have you tried to do it like this?

 Drawable greenProgressbar = context.getResources().getDrawable(R.drawable.custom_progressbargreen); 
+8
Jan 06 '15 at 10:11
source share

You should use "getDrawable (id, this.getTheme ())". This method is not recommended so far.

 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)); } 
0
Feb 16 '19 at 6:34
source share

I agree with the use of ContextCompact.getDrawable (Context context, int resID). This worked for me and my API 19 oriented apps.

0
Jul 05 '19 at 6:37
source share

Try the following:

 AppCompatResources.getDrawable(context, R.drawable.*) 
-one
Sep 19 '17 at 8:52 on
source share



All Articles