制作弹跳动画

15

我想要对图层进行弹跳动画。

我已经让图层从右边移到中心了,现在我想把它稍微向后移动,然后再回到中心。这样就会产生弹跳效果。

我认为可以通过以下方式进行平移来实现:

<translate
    android:duration="900"
    android:fromXDelta="100%p"
    android:toXDelta="0%p" />

<translate
    android:duration="900"
    android:fromXDelta="0%p"
    android:toXDelta="100%p" />

<translate
    android:duration="900"
    android:fromXDelta="70%p"
    android:toXDelta="0%p" />

这段代码没有起作用,我只能做到让层从左边到中间,然后动画停止。

我无法使用这段代码,因为它不能实现我想要的效果。

setInterpolator(AnimationUtils.loadInterpolator(this,
                        android.R.anim.bounce_interpolator));

非常感谢您的帮助。


你是否为你的动画指定了持续时间? - frogatto
3个回答

21
你可以使用BounceInterpolator来实现这个效果。在文档中有非常好的说明如何在XML中使用它。只需像这样拥有一个动画xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"

    android:interpolator="@android:anim/bounce_interpolator">

    <!-- Use your working translate animation here-->
    <translate
        android:duration="900"
        android:fromXDelta="100%p"
        android:toXDelta="0%p" />
</set>

1
谢谢提供的解决方案,但不是我要找的。这个动画一直在弹跳。我只需要“一次”弹跳。 - 5er
1
创建你自己的插值器,或者使用一个 repeat=1 + reverse 的加速减速插值器(看起来“类似”)。 - Martin Marconcini
1
我相信你想要的是一个超调插值器 @5er https://www.youtube.com/watch?v=6UL7PXdJ6-E - 1tSurge

4
请使用这个 XML。
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true"
    android:interpolator="@android:anim/bounce_interpolator">

    <scale
        android:duration="600"
        android:fromXScale="1.0"
        android:fromYScale="0.0"
        android:toXScale="1.0"
        android:toYScale="1.0" />

</set>

这将展示一个带有缩放的反弹效果,不同于平移(在某些情况下更加适用),了解更多请查看此处

3

在按钮或图片点击事件上添加代码

    final Animation myAnim = AnimationUtils.loadAnimation(getActivity(), R.anim.bounce);
    // Use bounce interpolator with amplitude 0.1 and frequency 15
    MyBounceInterpolator interpolator = new MyBounceInterpolator(0.1, 15);
    myAnim.setInterpolator(interpolator);
    imgVoiceSearch.startAnimation(myAnim);

请添加这个类

public class MyBounceInterpolator implements android.view.animation.Interpolator {
private double mAmplitude = 1;
private double mFrequency = 10;

public MyBounceInterpolator(double amplitude, double frequency) {
    mAmplitude = amplitude;
    mFrequency = frequency;
}

public float getInterpolation(float time) {
    return (float) (-1 * Math.pow(Math.E, -time / mAmplitude) *
            Math.cos(mFrequency * time) + 1);
}
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接