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

Jetpack Compose使用XML shape drawable时报XmlPullParserException如何解决?

错误根因

vectorResource() 方法仅支持加载 Android Vector 矢量图格式的 XML 文件,你使用的是 Shape Drawable 类型的资源,不属于矢量图范畴,解析时缺少矢量图必需的 viewportWidth、viewportHeight 等属性,因此抛出解析异常。

解决方案

方案1:使用 painterResource 加载(最简方案)

Jetpack Compose 提供的 painterResource 会自动识别资源类型,支持矢量图、Shape Drawable、位图等多种格式的资源加载,无需手动区分类型,修改代码如下:

@Composable
fun SplashScreen() {
    Box(
        modifier = Modifier.fillMaxSize()
    ) {
        Image(
            painter = painterResource(id = R.drawable.sp_rectangle_gradient_blue_purple),
            contentDescription = "Background",
            contentScale = ContentScale.FillBounds
        )
    }
}

方案2:直接设置为Box背景(无需嵌套Image)

如果不想额外嵌套Image组件,也可以直接获取Drawable实例绘制在Box背景上:

@Composable
fun SplashScreen() {
    val context = LocalContext.current
    val gradientDrawable = remember {
        ContextCompat.getDrawable(context, R.drawable.sp_rectangle_gradient_blue_purple) as GradientDrawable
    }
    Box(
        modifier = Modifier
            .fillMaxSize()
            .drawBehind {
                gradientDrawable.setBounds(0, 0, size.width.toInt(), size.height.toInt())
                gradientDrawable.draw(drawContext.canvas)
            }
    ) {
        // 页面子组件内容
    }
}

补充说明

你使用的 Compose 1.0.0-beta07 版本已经完整支持 painterResource 加载 Shape Drawable 资源,无需添加额外依赖。后续加载未知类型的drawable资源时,优先使用painterResource,避免指定imageVector/imageBitmap导致的类型不匹配问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 05:45:08