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

Android自定义ProgressBar遇空指针:decodeResource返回null求助

解决BitmapFactory解码Vector资源返回NullPointerException的问题

问题根源

BitmapFactory.decodeResource() 仅支持解码位图格式资源(如PNG、JPG),无法直接处理你从SVG转换来的Vector XML资源(VectorDrawable),因此返回null,而你直接将其赋值给非空类型的Bitmap变量,触发了NullPointerException。

解决方案

1. 正确将VectorDrawable转换为Bitmap

使用VectorDrawableCompat将Vector资源转为Bitmap,替换你原来的Bitmap初始化代码:

// 替换原来的直接赋值,改为在Activity的onCreate中调用该方法
private lateinit var batteryIcon: Bitmap

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    batteryIcon = getBatteryBitmap()
}

private fun getBatteryBitmap(): Bitmap {
    // 获取VectorDrawable实例,判空避免资源不存在的情况
    val vectorDrawable = VectorDrawableCompat.create(resources, R.drawable.ic_battery, theme) 
        ?: throw IllegalArgumentException("资源R.drawable.ic_battery不存在或格式错误")
    
    // 创建对应尺寸的Bitmap
    val bitmap = Bitmap.createBitmap(
        vectorDrawable.intrinsicWidth,
        vectorDrawable.intrinsicHeight,
        Bitmap.Config.ARGB_8888
    )
    val canvas = Canvas(bitmap)
    // 设置Drawable绘制边界并绘制到Bitmap
    vectorDrawable.setBounds(0, 0, canvas.width, canvas.height)
    vectorDrawable.draw(canvas)
    return bitmap
}

2. 检查资源配置是否正确

  • 确保ic_battery.xml放在res/drawable目录(不要放在drawable-v24等版本限定目录,避免低版本系统无法访问)
  • 检查资源文件名是否全小写、无特殊字符(Android资源文件名严格要求)
  • 打开ic_battery.xml确认根标签是<vector>,没有XML语法错误

3. 自定义View中更高效的实现(推荐)

如果你的CustomProgressBar需要绘制这个电池图标,无需提前转为Bitmap,直接在onDraw中绘制VectorDrawable更节省内存:

class CustomProgressBar @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val batteryDrawable: VectorDrawableCompat? = 
        VectorDrawableCompat.create(resources, R.drawable.ic_battery, context.theme)

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        batteryDrawable?.let { drawable ->
            // 根据你的布局需求调整绘制边界
            drawable.setBounds(10, 10, width - 10, height - 10)
            drawable.draw(canvas)
        }
    }
}

错误日志对应说明

你遇到的NullPointerException: decodeResource(...) must not be null,本质是BitmapFactory.decodeResource()返回了null,但你声明的private val batteryIcon: Bitmap是非空类型,Kotlin不允许将null赋值给非空变量,因此触发崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 21:58:34