欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

ClassCastException:AdaptiveIconDrawable cannot be cast to BitmapDrawable

发布时间:2023/12/10 编程问答 47 豆豆
生活随笔 收集整理的这篇文章主要介绍了 ClassCastException:AdaptiveIconDrawable cannot be cast to BitmapDrawable 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

Caused by: java.lang.ClassCastException: android.graphics.drawable.AdaptiveIconDrawable cannot be cast to android.graphics.drawable.BitmapDrawable
出现原因是因为应用适配了API 26的自适配图标adaptive-icon,使用下面的方法读取icon,读取到应用的默认的ICON图标是个adaptive-icon 类型,所以造成了强转出错

BitmapDrawable bd = (BitmapDrawable) FileManagerApplication.getContext().getResources().getDrawable(R.mipmap.ic_launcher_document);
Bitmap logoBmp = bd.getBitmap();

解决方法:

final Bitmap logoBmp = ImageThumbnail.getIconBitmap(FileManagerApplication.getContext(), R.mipmap.ic_launcher_document);
public static Bitmap getIconBitmap(Context context, int iconId) {
        try {
            Drawable icon = ContextCompat.getDrawable(context, iconId);
            if (icon == null) {
                return null;
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && icon instanceof AdaptiveIconDrawable) {
                Bitmap bitmap = Bitmap.createBitmap(icon.getIntrinsicWidth(), icon.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
                Canvas canvas = new Canvas(bitmap);
                icon.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
                icon.draw(canvas);
                return bitmap;
            } else {
                return ((BitmapDrawable) icon).getBitmap();
            }
        } catch (Exception e) {
            return null;
        }
    }

总结

以上是生活随笔为你收集整理的ClassCastException:AdaptiveIconDrawable cannot be cast to BitmapDrawable的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。