Android 不推荐使用getDrawable(int id)。如何设置图像?

Android 不推荐使用getDrawable(int id)。如何设置图像?,android,Android,有问题!getDrawable()在API 22中被弃用。所以,如果我用min API 16制作一个应用程序,我如何设置图像 我看到我可以使用getDrawable(intid,theme),但这是在API21中添加的,所以我不能使用它 我尝试过setImageDrawable(ResourcesCompat.getDrawable(getResources(),R.drawable.drawableName,null)),但这也不起作用。同样对于ContextCompat或getApplica

有问题!getDrawable()在API 22中被弃用。所以,如果我用min API 16制作一个应用程序,我如何设置图像

我看到我可以使用getDrawable(intid,theme),但这是在API21中添加的,所以我不能使用它

我尝试过
setImageDrawable(ResourcesCompat.getDrawable(getResources(),R.drawable.drawableName,null))
,但这也不起作用。同样对于ContextCompat或getApplicationContext()也不起作用

private ImageView weatherIcon;
weatherIcon=(ImageView)findViewById(R.id.weatherIcon);
if(weatherReportList.size()>0){
            DailyWeatherReport report=weatherReportList.get(0);
            switch (report.getWeather()){
                case DailyWeatherReport.WEATHER_TYPE_CLOUDS:
                    weatherIcon.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.cloudy, null));
                    weatherIconMini.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.cloudy, null));
                case DailyWeatherReport.WEATHER_TYPE_RAIN:
                    weatherIcon.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.rainy));
                    weatherIconMini.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.rainy, null));

                default:
                    weatherIcon.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.sunny, null));
                    weatherIconMini.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.sunny, null));


            }
这不是那篇文章的翻版。我已经尝试了那里的所有方法,但没有一种有效。

你可以这样尝试

 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
    return context.getResources().getDrawable(resource);
} else {
    return context.getResources().getDrawable(resource, null);
}
if(Build.VERSION.SDK\u INT
可能会帮助您

您可以使用

yourImageView.setImageDrawable(ContextCompat.getDrawable(context, /*your drawable like R.drawable.drawableName*/));

似乎我的项目有一个bug,但我无法识别它。如果我尝试其他项目,它可以与上面的任何答案一起工作

检查此处:虽然
getDrawable()
已被弃用,但它现在仍然可以工作,因此您的代码可能在其他地方出错,我通过getContext获取上下文?是的,您可以,您也可以使用
getActivity()
如果它是片段或
您的活动。这是
getApplicationContext()
如果是活动。但这也不起作用:(也许我的代码有问题,但我不这么认为。
weatherIcon.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),R.drawable.rainy));
如果此代码在活动中,我总是建议将“this”作为上下文。