getDrawable(int id)已被弃用。我该如何设置一张图片?

3

有一个问题!在API 22中,getDrawable()已经被弃用。因此,如果我使用最小的API 16制作一个应用程序,我该如何设置图片?

我看到可以使用getDrawable(int id, theme),但这是在API 21中添加的,所以我无法使用它。

我尝试过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));


            }

这不是那篇帖子的副本。我已经尝试了那里所有的方法,但它们都没有起作用。


请查看此处:https://dev59.com/NV4b5IYBdhLWcg3wfx1I#29041466 - Aspicas
可能是Android getResources().getDrawable() deprecated API 22的重复问题。 - F. Kauder
尽管getDrawable()方法已被弃用,但它仍然可以正常工作,所以可能是你的代码其他地方出了问题。 - Harlan
3个回答

7

你可以使用

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

我可以通过getContext获取上下文吗? - Andrei Pascale
是的,你可以这样做,如果它是一个片段,你也可以使用getActivity(),或者如果是活动,则可以使用yourActivity.thisgetApplicationContext() - Deepak Goyal
但这也不起作用。:( 也许我的代码有问题,但我不这么认为。 - Andrei Pascale
weatherIcon.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),R.drawable.rainy)); - Andrei Pascale
如果这段代码在一个Activity中,我建议始终将“this”作为上下文。 - cherry-wave

2
您可以尝试以下方法:
 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
    return context.getResources().getDrawable(resource);
} else {
    return context.getResources().getDrawable(resource, null);
}

可能会对您有所帮助


0

看起来我的项目有一个bug,但是我无法找出它。如果我尝试在其他项目上,这个问题都能解决。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接