对于新的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);
其他回答
en-api级别14
marker.setIcon(ResourcesCompat.getDrawable(getResources(), R.drawable.miubicacion, null));
替换此行:getResources().getDrawable(R.drawable.your_drawable)
使用ResourcesCompat.getDrawable(getResources(),R.draable.your_drawable,null)
EDIT
ResourcesCompat现在也被弃用。但您可以使用此选项:
ContextCompat.getDrawable(this,R.drawable.your_drawable)(这里是上下文)
有关详细信息,请单击以下链接:ContextCompat
您可以使用
ContextCompat.getDrawable(getApplicationContext(),R.drawable.example);
这是我的工作
根据要加载的绘图类型,您可以选择以正确的方式(以及将来的证明)处理此弃用:
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);
在Kotlin,您可以使用扩展
fun Context.getMyDrawable(id : Int) : Drawable?{
return ContextCompat.getDrawable(this, id)
}
然后使用like
context.getMyDrawable(R.drawable.my_icon)