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

如何在Jetpack Compose中实现Animated Vector Drawable替代废弃API

Jetpack Compose 使用 Animated Vector Drawable 的最优实现方案

由于compose.animation:animation-graphics库下的 Animated Vector Drawable 相关API即将被移除,官方推荐使用androidx.compose.ui:ui-res库提供的稳定API实现同等功能。

前置依赖

首先需要在模块级build.gradle中引入ui-res依赖,版本需和项目使用的Compose版本保持一致:

dependencies {
    implementation "androidx.compose.ui:ui-res:1.6.0" // 替换为你的Compose对应版本
}

基础实现代码

对应原有逻辑的替换代码如下:

import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.animatedVectorResource
import androidx.compose.ui.res.AnimatedVectorPainter
import androidx.compose.ui.unit.dp

// 组合函数内逻辑
var atEnd by remember { mutableStateOf(false) }
// 加载你的Animated Vector Drawable资源
val avdRes = animatedVectorResource(R.drawable.your_avd_res_id)

Image(
    painter = AnimatedVectorPainter(
        animatedVectorResource = avdRes,
        atEnd = atEnd
    ),
    contentDescription = "你的内容描述",
    modifier = Modifier
        .size(64.dp)
        .clickable {
            atEnd = !atEnd
        }
)

功能扩展

  • 需要监听动画完成状态的场景,可以传入onAtEndChanged回调:
AnimatedVectorPainter(
    animatedVectorResource = avdRes,
    atEnd = atEnd,
    onAtEndChanged = { isAtEnd ->
        // 动画播放完成时触发
        if (isAtEnd) {
            // 正向播放完成逻辑
        } else {
            // 反向播放完成逻辑
        }
    }
)
  • 动画的时长、插值器、属性变化规则不需要在Compose代码中配置,直接在AVD的XML资源文件中修改即可,Compose会自动读取配置执行动画。

API说明

官方对旧API的说明如下:

注意:该API为临时版本,为鼓励使用异步资源加载,后续大概率会被移除。

新的AnimatedVectorPainter基于异步资源加载实现,不会阻塞UI线程渲染,性能更优,也是官方长期支持的稳定实现方案。

内容的提问来源于stack exchange,提问作者Loïc Jackotin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 06:06:02