Android: Alternative for context.getDrawable()

2019-01-30 17:07发布

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().

5条回答
Juvenile、少年°
2楼-- · 2019-01-30 17:45

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

Hope this will help you

查看更多
干净又极端
3楼-- · 2019-01-30 17:46

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

Drawable greenProgressbar = context.getResources().getDrawable(R.drawable.custom_progressbargreen);
查看更多
Summer. ? 凉城
4楼-- · 2019-01-30 17:47

Try adding a getResources() after the context, so this:

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

should work.

查看更多
小情绪 Triste *
5楼-- · 2019-01-30 18:02

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.***)

查看更多
来,给爷笑一个
6楼-- · 2019-01-30 18:04

Try this:

AppCompatResources.getDrawable(context, R.drawable.*)
查看更多
登录 后发表回答