对于新的android API 22,getResources().getDrawable()现在已被弃用。现在最好的方法是只使用getDrawable()。
什么改变了?
对于新的android API 22,getResources().getDrawable()现在已被弃用。现在最好的方法是只使用getDrawable()。
什么改变了?
当前回答
这只是我如何在数组中修复问题以加载listView的一个示例,希望它有所帮助。
mItems = new ArrayList<ListViewItem>();
// Resources resources = getResources();
// mItems.add(new ListViewItem(resources.getDrawable(R.drawable.az_lgo), getString(R.string.st_az), getString(R.string.all_nums)));
// mItems.add(new ListViewItem(resources.getDrawable(R.drawable.ca_lgo), getString(R.string.st_ca), getString(R.string.all_nums)));
// mItems.add(new ListViewItem(resources.getDrawable(R.drawable.co_lgo), getString(R.string.st_co), getString(R.string.all_nums)));
mItems.add(new ListViewItem(ResourcesCompat.getDrawable(getResources(), R.drawable.az_lgo, null), getString(R.string.st_az), getString(R.string.all_nums)));
mItems.add(new ListViewItem(ResourcesCompat.getDrawable(getResources(), R.drawable.ca_lgo, null), getString(R.string.st_ca), getString(R.string.all_nums)));
mItems.add(new ListViewItem(ResourcesCompat.getDrawable(getResources(), R.drawable.co_lgo, null), getString(R.string.st_co), getString(R.string.all_nums)));
其他回答
Build.VERSION_CODES.LOLLIOP现在应更改为BuildVersionCodes.LOLLIPOP即:
if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop) {
this.Control.Background = this.Resources.GetDrawable(Resource.Drawable.AddBorder, Context.Theme);
} else {
this.Control.Background = this.Resources.GetDrawable(Resource.Drawable.AddBorder);
}
试试这个
ContextCompat.getDrawable(getActivity(), R.drawable.drawable_resource_name);
根据要加载的绘图类型,您可以选择以正确的方式(以及将来的证明)处理此弃用:
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);
现在您需要这样实现
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //>= API 21
//
} else {
//
}
只需执行一行代码就足够了,ContextCompat.getDrawable将处理所有问题
ContextCompat.getDrawable(this, R.drawable.your_drawable_file)
对于一些即使在应用了这个线程的建议(我以前也是这样的)之后仍然需要解决这个问题的人,请在Application类上添加这行,onCreate()方法
AppCompatDelegate.setComptVectorFromResourcesEnabled(true)
正如这里和这里所建议的,有时需要从资源中访问向量,尤其是在处理菜单项等时