对于新的android API 22,getResources().getDrawable()现在已被弃用。现在最好的方法是只使用getDrawable()。

什么改变了?


当前回答

对于一些即使在应用了这个线程的建议(我以前也是这样的)之后仍然需要解决这个问题的人,请在Application类上添加这行,onCreate()方法

AppCompatDelegate.setComptVectorFromResourcesEnabled(true)

正如这里和这里所建议的,有时需要从资源中访问向量,尤其是在处理菜单项等时

其他回答

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(getApplicationContext(),R.drawable.example);

这是我的工作

替换此行:getResources().getDrawable(R.drawable.your_drawable)

使用ResourcesCompat.getDrawable(getResources(),R.draable.your_drawable,null)

EDIT

ResourcesCompat现在也被弃用。但您可以使用此选项:

ContextCompat.getDrawable(this,R.drawable.your_drawable)(这里是上下文)

有关详细信息,请单击以下链接:ContextCompat

en-api级别14

marker.setIcon(ResourcesCompat.getDrawable(getResources(), R.drawable.miubicacion, null));

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)

希望这对你有帮助。谢谢。