对于新的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)));
其他回答
您可以使用
ContextCompat.getDrawable(getApplicationContext(),R.drawable.example);
这是我的工作
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)
希望这对你有帮助。谢谢。
试试这个
ContextCompat.getDrawable(getActivity(), R.drawable.drawable_resource_name);
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));
}
编辑:查看我的博客文章以获得更完整的解释
您应该使用支持库中的以下代码:
ContextCompat.getDrawable(context, R.drawable.***)
使用此方法相当于调用:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return resources.getDrawable(id, context.getTheme());
} else {
return resources.getDrawable(id);
}
从API 21开始,您应该使用getDrawable(int,Theme)方法而不是getDrawble(int)方法,因为它允许您获取与给定屏幕密度/主题的特定资源ID相关联的可绘制对象。调用不推荐使用的getDrawable(int)方法等同于调用getDrawble(int,null)。