3

Have a question! getDrawable() is deprecated in API 22. So, if I make an app with the min API 16, how can I set an image?

I saw that I can use getDrawable(int id, theme) , but this was added in API 21, so I can't use it.

I've tried setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.drawableName, null)) but this doesn't work either. Also with ContextCompat or getApplicationContext() it doesn't work.

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));


            }

This is not a duplicate of that post. I've tried all the methods from there but none on them worked.

Andrei Pascale
  • 232
  • 1
  • 3
  • 16
  • Check here: http://stackoverflow.com/a/29041466/3626214 – Aspicas Jul 22 '16 at 11:34
  • Possible duplicate of [Android getResources().getDrawable() deprecated API 22](http://stackoverflow.com/questions/29041027/android-getresources-getdrawable-deprecated-api-22) – F. Kauder Jul 22 '16 at 11:34
  • Though the `getDrawable()` is deprecated, but it could still work right now, so maybe something wrong in your code somewhere else – Harlan Jul 22 '16 at 14:42

3 Answers3

7

you can use

yourImageView.setImageDrawable(ContextCompat.getDrawable(context, /*your drawable like R.drawable.drawableName*/));
Deepak Goyal
  • 4,747
  • 2
  • 21
  • 46
2

You can try this way,

 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
    return context.getResources().getDrawable(resource);
} else {
    return context.getResources().getDrawable(resource, null);
}

may helps you

Sathish Kumar J
  • 4,280
  • 1
  • 20
  • 48
0

It seems that my project has a bug, but I can't identify it. If I try on other projects, it works with any of the answers above.

Andrei Pascale
  • 232
  • 1
  • 3
  • 16