当前位置:网站首页>'getDrawable(int)' is deprecated,getDrawable过时

'getDrawable(int)' is deprecated,getDrawable过时

2022-06-10 11:35:00 yechaoa

getDrawable(int)在API 21(5.0)已经过时了

5.0之后使用:

ContextCompat.getDrawable(context, R.drawable.your_drawable)

例如:

imageView.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.icon));

源码

 public static final Drawable getDrawable(Context context, @DrawableRes int id) {
        final int version = Build.VERSION.SDK_INT;
        if (version >= 21) {
            return ContextCompatApi21.getDrawable(context, id);
        } else if (version >= 16) {
            return context.getResources().getDrawable(id);
        } else {
            // Prior to JELLY_BEAN, Resources.getDrawable() would not correctly
            // retrieve the final configuration density when the resource ID
            // is a reference another Drawable resource. As a workaround, try
            // to resolve the drawable reference manually.
            final int resolvedId;
            synchronized (sLock) {
                if (sTempValue == null) {
                    sTempValue = new TypedValue();
                }
                context.getResources().getValue(id, sTempValue, true);
                resolvedId = sTempValue.resourceId;
            }
            return context.getResources().getDrawable(resolvedId);
        }
    }

可以看出也是做了高版本低版本兼容的

原网站

版权声明
本文为[yechaoa]所创,转载请带上原文链接,感谢
https://cloud.tencent.com/developer/article/2019732