我在我的项目中使用了context.getDrawable()
:
Drawable greenProgressbar = context.getDrawable(R.drawable.custom_progressbargreen);
但是Eclipse给了我一个错误,它需要一个Minimum API level of 21
。这意味着在快速谷歌搜索后,我的APP只能在Android 5.0
上使用。由于并非所有设备都使用此版本的android,我想为context.getDrawable()
提供替代方案。
根据SDK 22文档,以前已接受的方法已被弃用:
在android.os.Build.VERSION_CODES#JELLY_BEAN之前,当此处传递的资源ID是另一个Drawable资源的别名时,此函数将无法正确检索最终配置密度。这意味着如果别名资源的密度配置与实际资源不同,则返回的Drawable的密度将不正确,从而导致错误的缩放。
正如在this answer中指出的更好的解决方案是使用ContextCompat:ContextCompat.getDrawable(context, R.drawable.***)
尝试在上下文后添加getResources()
,所以这样:
Drawable greenProgressbar = context.getResources().getDrawable(R.drawable.custom_progressbargreen);
应该管用。
我之前遇到过类似的问题。你试过这样做吗?
Drawable greenProgressbar = context.getResources().getDrawable(R.drawable.custom_progressbargreen);
我有同样的情况,我想引用getDrawable()方法,现在已弃用。
我用过的,
myButton.setImageDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.ic_btn_off));
希望对你有帮助
我同意使用ContextCompact.getDrawable(Context context,int resID)。它适用于我和我的应用程序目标API 19。
你应该使用“getDrawable(id,this.getTheme())”。此方法至今尚未弃用。
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));
}
试试这个:
AppCompatResources.getDrawable(context, R.drawable.*)