java.lang.ClassCastException: android.graphics.drawable.StateListDrawable cannot be cast to andro...

背景:

Android8.0 之后图标需要兼容方案 多了个圆形的图标兼容完之后获取图标出现了
java.lang.ClassCastException: android.graphics.drawable.StateListDrawable cannot be cast to android.graphics.drawable.BitmapDrawable
一下是出错的代码


image.png

API 26 你会发现 默认的ICON图标是个adaptive-icon 类型所以造成了强转出错


image.png

image.png

解决方案

@NonNull
private Bitmap getBitmapFromDrawable(@NonNull Drawable drawable) {
    final Bitmap bmp = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    final Canvas canvas = new Canvas(bmp);
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);
    return bmp;
}

调用方法


image.png

参考资料:https://stackoverflow.com/questions/44447056/convert-adaptiveicondrawable-to-bitmap-in-android-o-preview?noredirect=1&lq=1

你可能感兴趣的:(java.lang.ClassCastException: android.graphics.drawable.StateListDrawable cannot be cast to andro...)