【问题标题】:Why isn't this android animation doing anything?为什么这个android动画没有做任何事情?
【发布时间】:2018-09-21 17:29:18
【问题描述】:

我正在尝试使用新风格的 Android 属性动画器(而不是旧的视图动画)来创建动画以水平摇动视图。

我在/res/animator/shake.xml中编写了以下 XML 动画器

<?xml version="1.0" encoding="utf-8"?>
<objectAnimator
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:propertyName="translationX"
    android:duration="100"
    android:valueFrom="0f"
    android:valueTo="20f"
    android:valueType="floatType"
    android:interpolator="@android:anim/linear_interpolator"
    android:repeatCount="7"
    android:repeatMode="reverse"/>

我创建了以下 Kotlin 扩展方法来在任何视图上播放动画:

fun View.shake() {
    AnimatorInflater.loadAnimator(context, R.animator.shake).apply {
        setTarget(this)
        start()
    }
}

但是,当我调用动画时,什么都没有发生,我不知道为什么。

【问题讨论】:

    标签: android kotlin android-animation android-xml objectanimator


    【解决方案1】:

    不要将setTarget(this)start() 放入apply{}

    用这个替换你的代码:

    fun View.shake() {
        val al = AnimatorInflater.loadAnimator(context, R.animator.shake)
        al.setTarget(this)
        al.start()
    }
    

    或者你可以这样做:

    AnimatorInflater.loadAnimator(context, R.animator.shake).apply {
            setTarget(this@shake)
            start()
        }
    

    之前的 this 指的是 AnimatorInflater.loadAnimator 而不是 View,因此只需将其替换为 this@shake 即可将其引用到您正在应用动画的 view

    【讨论】:

    • 这是正确的,但我无法将其标记为已接受,除非您解释我做错的原因。
    猜你喜欢
    • 2021-05-06
    • 2021-08-11
    • 2021-12-20
    • 2011-07-25
    • 2015-06-30
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多