Android: context.getDrawable()的替代品

我在我的项目中使用了这样的 context.getDrawable():

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

但是 Eclipse 给了我一个错误,它需要一个 Minimum API level of 21。这将意味着经过一个快速谷歌搜索我的应用程序将只能在 Android 5.0上使用。因为并非所有的设备都在使用这个版本的机器人,我想有一个替代 context.getDrawable()

72962 次浏览
Drawable greenProgressbar = context.getResources().getDrawable(R.drawable.custom_progressbargreen);

Add a getResources() after the context:

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

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

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));
AppCompatResources.getDrawable(context, R.drawable.*)

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.

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

btn.setImageResource(R.drawable.ic_XXX)

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)