简体   繁体   中英

Android: .getDrawable deprecated, minimum SDK 17 solution?

I am currently reading through the Head First Android Development book.

This question is regarding code in chapter 13, with a link to the specific file below:

https://github.com/dogriffiths/HeadFirstAndroid/blob/master/chapter14/BitsAndPizzas/app/src/main/java/com/hfad/bitsandpizzas/CaptionedImagesAdapter.java

The code below uses a deprecated method, .getDrawable:

Drawable drawable = cardView.getResources().getDrawable(imageIds[position]);

For new SDKs this can be resolved by changing the code to:

Drawable drawable = cardView.getResources().getDrawable(imageIds[position], null);

However, I cannot get the code working for a minimum SDK of 17, and have tried using ContextCompat. The previously used compatibility solution I found was deprecated.

Thank you

ContextCompat.getDrawable(Context context, int id) is not deprecated and is the correct method to use in this scenario.

If for whatever reason you don't want to use ContextCompat , you can always just use the same code it uses :

public static final Drawable getDrawable(Context context, int id) {
    final int version = Build.VERSION.SDK_INT;
    if (version >= 21) {
        return context.getDrawable(id);
    } else {
        return context.getResources().getDrawable(id);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM