You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Fresco加载BitmapDrawable:setImageDrawable废弃后的替代实现咨询

替换废弃的setImageDrawable方法加载BitmapDrawable的方案

嘿,我来帮你搞定这个废弃方法的替换问题~

首先先澄清一个小误区:ImageView原生的setImageDrawable()方法其实并没有被废弃,但如果你的场景里确实遇到了该方法被标记为废弃的情况(比如自定义View的实现),或者你是因为BitmapDrawable的旧构造方法废弃而困惑,这里有两个实用的替代方案:

方案一:直接用setImageBitmap()(推荐)

既然你已经生成了裁剪后的Bitmap对象(croppedIcon),完全没必要多一步转成Drawable的操作,直接调用ImageView的setImageBitmap()方法就行,这是更直接高效的方式:

// 获取目标ImageView实例
ImageView targetImageView = activity.findViewById(R.id.your_image_view_id);
Bitmap croppedIcon = cropImage(activity, resourceId);
if (croppedIcon != null) {
    targetImageView.setImageBitmap(croppedIcon);
}

方案二:正确创建BitmapDrawable后设置(若必须用Drawable)

如果你的业务逻辑确实需要将Bitmap转为Drawable再设置,要注意旧的BitmapDrawable(Bitmap)构造方法在API 29+已废弃,需要使用带Resources参数的构造方法来创建,之后再设置到View上:

ImageView targetImageView = activity.findViewById(R.id.your_image_view_id);
Bitmap croppedIcon = cropImage(activity, resourceId);
if (croppedIcon != null) {
    // 传入当前Activity的Resources创建BitmapDrawable
    BitmapDrawable drawable = new BitmapDrawable(activity.getResources(), croppedIcon);
    // 若需要更好的兼容性,可用DrawableCompat包装
    // Drawable wrappedDrawable = DrawableCompat.wrap(drawable);
    targetImageView.setImageDrawable(drawable);
}

这样就能完美替代原来的废弃方法,同时保证在不同Android版本上的兼容性啦~

内容的提问来源于stack exchange,提问作者HyperX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:29:50