Make bounce animation

这一生的挚爱 提交于 2020-01-12 05:11:35

问题


I would like to do bounce animation of layer.

I have done that layer comes from right to center, now I would like to move it a little back and then back to center. That would create bounce effect.

I was thinking that I can do it with a translate like this:

<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" />

Well this code does not working, only thing I can achieve is that Layer comes from left to center, and then animation stops.

I cannot use this code: because it does not achieve what I want

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

Any help would be appreciated.


回答1:


You can use the BounceInterpolator to have this effect. The docs contain a very good description how to use it in XML. Just have a animation xml like this:

<?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>



回答2:


use this 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>

This will show bounce effect with scale ,different from translate,(fits better in some situations),for more check THIS out..




回答3:


Add code on button or image click

    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);

Add this class

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);
}
}


来源:https://stackoverflow.com/questions/23937748/make-bounce-animation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!