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

Android Glance Widget:如何为带圆角的Shape Drawable着色?

动态修改Shape Drawable颜色的响应式方案(Glance-beta01 + Android 12及以下)

针对Glance-beta01在Android 12及以下无法使用CornerRadius修饰符,且需要动态修改Shape Drawable颜色并保持响应式的需求,提供两种可行方案:

方案一:代码中动态创建ShapeDrawable

直接在Glance代码里实例化ShapeDrawable,通过State驱动颜色更新,无需依赖xml文件,天然支持响应式:

  • 利用remember结合颜色参数缓存ShapeDrawable实例,避免重复创建
  • 颜色变化时直接修改Drawable的画笔颜色,并触发View重绘
@Composable
fun ResponsiveRoundedBox(color: Color) {
    val cornerRadius = LocalContext.current.resources.getDimension(R.dimen.corner_radius_outside)
    val shapeDrawable = remember(color) {
        ShapeDrawable(RoundRectShape(CornerRadius(cornerRadius))).apply {
            paint.color = color.toArgb()
        }
    }

    AndroidView(
        factory = { context ->
            View(context).apply {
                background = shapeDrawable
            }
        },
        update = { view ->
            shapeDrawable.paint.color = color.toArgb()
            view.background = shapeDrawable // 触发View重绘,确保颜色更新生效
        }
    )
}

方案二:通过Tint复用原xml Shape Drawable

保留原有的xml Shape Drawable,通过设置背景tint实现动态颜色修改,同样支持响应式:

  • 原xml需移除<solid>标签的固定颜色(或保留默认色,后续被tint覆盖)
  • 利用ColorStateList将动态颜色绑定到View的背景tint属性,颜色变化时更新tint即可
<!-- 修改后的shape_drawable.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="@dimen/corner_radius_outside" />
</shape>
@Composable
fun ResponsiveRoundedBox(color: Color) {
    val context = LocalContext.current
    val shapeDrawable = remember {
        ContextCompat.getDrawable(context, R.drawable.shape_drawable)!!
    }

    AndroidView(
        factory = { viewContext ->
            View(viewContext).apply {
                background = shapeDrawable
                backgroundTint = ColorStateList.valueOf(color.toArgb())
            }
        },
        update = { view ->
            view.backgroundTint = ColorStateList.valueOf(color.toArgb())
        }
    )
}

两种方案均无需转Bitmap,能跟随Glance的State变化实时更新UI,保持响应式特性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 17:35:16