对于新的android API 22,getResources().getDrawable()现在已被弃用。现在最好的方法是只使用getDrawable()。
什么改变了?
对于新的android API 22,getResources().getDrawable()现在已被弃用。现在最好的方法是只使用getDrawable()。
什么改变了?
当前回答
如果您需要从其他SDK 23及以上版本的应用程序中提取
PackageManager manager = getApplicationContext().getPackageManager();
Resources resources = null;
try {
resources = manager.getResourcesForApplication("com.anyapp");
}
catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
assert resources != null;
Drawable notiIcon = ResourcesCompat.getDrawable(resources, current.iconId/* drawable resource id */, null);
其他回答
getResources().getDrawable()在API级别22中被弃用。现在我们必须添加主题:
getDrawable(int id,Resources.Theme主题)(在API级别21中添加)
这是一个示例:
myImgView.setImageDrawable(getResources().getDrawable(R.drawable.myimage, getApplicationContext().getTheme()));
以下是如何验证更高版本的示例:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //>= API 21
myImgView.setImageDrawable(getResources().getDrawable(R.drawable.myimage, getApplicationContext().getTheme()));
} else {
myImgView.setImageDrawable(getResources().getDrawable(R.drawable.myimage));
}
根据要加载的绘图类型,您可以选择以正确的方式(以及将来的证明)处理此弃用:
A) 具有主题属性的绘图
ContextCompat.getDrawable(getActivity(), R.drawable.name);
您将按照“活动”主题的指示获得一个样式化的Drawable。这可能就是你需要的。
B) 无主题属性的绘图
ResourcesCompat.getDrawable(getResources(), R.drawable.name, null);
你会像以前一样得到你的无样式抽屉。请注意:ResourcesCompat.getDrawable()未被弃用!
EXTRA)具有来自另一个主题的主题属性的绘图
ResourcesCompat.getDrawable(getResources(), R.drawable.name, anotherTheme);
getDrawable(int drawable)在API级别22中被弃用。有关参考,请参阅此链接。
现在,为了解决这个问题,我们必须通过一个新的构造器以及id,如:-
getDrawable(int id, Resources.Theme theme)
对于解决方案,请这样做:-
在Java中:-
ContextCompat.getDrawable(getActivity(), R.drawable.name);
or
imgProfile.setImageDrawable(getResources().getDrawable(R.drawable.img_prof, getApplicationContext().getTheme()));
在Kotlin:-
rel_week.background=ContextCompat.getDrawable(this.requireContext(), R.color.colorWhite)
or
rel_day.background=resources.getDrawable(R.drawable.ic_home, context?.theme)
希望这对你有帮助。谢谢。
现在您需要这样实现
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //>= API 21
//
} else {
//
}
只需执行一行代码就足够了,ContextCompat.getDrawable将处理所有问题
ContextCompat.getDrawable(this, R.drawable.your_drawable_file)
如果您的目标SDK>21(棒棒糖或5.0),请使用
context.getDrawable(R.drawable.your_drawable_name)
参见文档