简体   繁体   English

Android:不建议使用.getDrawable,最低的SDK 17解决方案?

[英]Android: .getDrawable deprecated, minimum SDK 17 solution?

I am currently reading through the Head First Android Development book. 我目前正在阅读《 Head First Android开发》一书。

This question is regarding code in chapter 13, with a link to the specific file below: 这个问题是关于第13章中的代码的,下面是指向特定文件的链接:

https://github.com/dogriffiths/HeadFirstAndroid/blob/master/chapter14/BitsAndPizzas/app/src/main/java/com/hfad/bitsandpizzas/CaptionedImagesAdapter.java 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: 以下代码使用了不赞成使用的方法.getDrawable:

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

For new SDKs this can be resolved by changing the code to: 对于新的SDK,可以通过将代码更改为:

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. 但是,我无法使代码在最低SDK为17的情况下工作,并尝试使用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. 不建议弃用ContextCompat.getDrawable(Context context, int id) ,它是在这种情况下使用的正确方法。

If for whatever reason you don't want to use ContextCompat , you can always just use the same code it uses : 如果出于某种原因您不想使用ContextCompat ,则始终可以使用使用的相同代码

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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