You need to enable JavaScript to run this app. 如何在MotionLayout关键帧中修改Lottie的lottie_rawRes等自定义属性
优惠活动
大模型
产品
解决方案
定价
更多

如何在MotionLayout关键帧中修改Lottie的lottie_rawRes等自定义属性

在MotionLayout关键帧修改Lottie及自定义属性的配置方法

你要在关键帧位置修改任意View的属性,核心逻辑就是在KeyAttribute节点内部嵌套CustomAttribute标签,遵循MotionLayout的反射匹配规则,和约束集终点的自定义属性配置逻辑一致,只是生效时机从“到达约束集终点”变成了“走到关键帧对应的进度位置”。

先修正你现有代码里的常见配置错误

MotionLayout 配置CustomAttribute时,会通过反射匹配目标View的对应setter方法:你填写的motion:attributeName,会自动拼接成setXxx()方法去调用。
你当前代码里有两个会导致配置不生效的问题:

  1. 属性名写错:把Lottie的属性名写成lottie_rawRes是找不到对应方法的——LottieAnimationView加载raw资源的对应方法是setAnimation(int rawResId),所以正确的attributeName应该写animation,而不是布局xml里的标签属性名lottie_rawRes。
  2. 值类型写错:raw资源是int类型的资源id,不能用motion:customStringValue传值,必须用motion:customIntegerValue字段,直接填资源引用@raw/xxx即可,系统会自动解析成对应的int值。

修正后的完整配置示例

<Transition
    motion:autoTransition="animateToEnd"
    motion:constraintSetEnd="@layout/motion_splash_screen_end"
    motion:constraintSetStart="@layout/motion_splash_screen_start"
    motion:duration="5000">
    <KeyFrameSet>
        <!-- 50%进度位置的关键帧,配置自定义属性 -->
        <KeyAttribute
            motion:framePosition="50"
            motion:motionTarget="@+id/splashSun">
            <!-- 切换Lottie动画资源 -->
            <CustomAttribute
                motion:attributeName="animation"
                motion:customIntegerValue="@raw/your_middle_lottie" />
            <!-- 示例:同时可以在这个关键帧修改其他任意属性 -->
            <CustomAttribute
                motion:attributeName="rotation"
                motion:customFloatValue="180" />
        </KeyAttribute>

        <KeyAttribute
            android:alpha="0"
            motion:framePosition="85"
            motion:motionTarget="@+id/splashAppName"/>
        <KeyAttribute
            android:alpha="1"
            motion:framePosition="95"
            motion:motionTarget="@+id/splashAppName"/>
    </KeyFrameSet>
</Transition>

<!-- 约束集终点的自定义属性,修正后写法 -->
<ConstraintSet android:id="@layout/motion_splash_screen_end">
    <Constraint
        android:id="@+id/splashClouds1">
        <CustomAttribute
            motion:attributeName="animation"
            motion:customIntegerValue="@raw/weather_moon_clear" />
    </Constraint>
</ConstraintSet>

实际开发注意事项

  • 不同类型的属性值必须匹配对应字段:字符串类型用customStringValue、颜色值用customColorValue、浮点属性用customFloatValue、整数/资源引用用customIntegerValue、布尔属性用customBooleanValue,类型不匹配会导致反射调用失败,属性完全不生效。
  • 自定义属性不会做补间插值:MotionLayout只会在进度走到对应关键帧位置的瞬间,立刻调用目标View的setter方法,不会在两个关键帧之间平滑过渡自定义属性值。比如在50%进度切换Lottie资源,就是进度走到50%的瞬间直接替换动画,没有平滑切换效果。
  • Lottie切换资源后不会自动播放:xml配置只会触发setAnimation()完成资源加载,不会自动启动播放,如果需要切动画后自动播放,需要在代码里监听MotionLayout的进度回调,进度到达对应关键帧位置时手动调用playAnimation()即可。
  • 其他自定义View的属性配置没有特殊限制:只要找到目标View的setter方法,把方法名去掉set前缀、首字母小写作为attributeName,选对值类型就能配置,不管是系统View还是自定义控件都通用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.17 09:57:04