Android: Alternative for context.getDrawable()

淺唱寂寞╮ 提交于 2019-11-28 04:02:52
user2417480

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

glm9637

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

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

should work.

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

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

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

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

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

Nando

Try this:

AppCompatResources.getDrawable(context, R.drawable.*)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!