如何以编程方式制作动画

时间:2016-07-26 15:56:52

标签: android animation

例如,xml动画:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true">

<!-- Rotate -->
<rotate
    android:duration="500"
    android:fromDegrees="30"
    android:interpolator="@android:anim/linear_interpolator"
    android:pivotX="50%"
    android:pivotY="50%"
    android:repeatCount="4"
    android:repeatMode="reverse"
    android:toDegrees="0"/>

<!--Move-->
<translate
    android:duration="1000"
    android:fromXDelta="0%"
    android:fromYDelta="150%"
    android:interpolator="@android:anim/linear_interpolator"
    android:toXDelta="0%"
    android:toYDelta="0%"/>

<!--Fade In-->
<alpha
    android:duration="2000"
    android:fromAlpha="0.0"
    android:interpolator="@android:anim/decelerate_interpolator"
    android:toAlpha="1.0"/>

</set>

是否可以通过java代码创建它?

1 个答案:

答案 0 :(得分:5)

你是否尝试过这样:

// when getting anims 
Animation animRotate = AnimationUtils.loadAnimation(context, R.anim.rotate);
Animation animMove = AnimationUtils.loadAnimation(context, R.anim.move);
Animation animFadeIn = AnimationUtils.loadAnimation(context, R.anim.fade_in);

如果您想以编程方式执行此操作:

我在我的项目中使用这种方式:

view.animate()
            .scaleY(1)
             //just wanted to show you possible methods you can add more
            .rotationY()
            .alpha()
            .setStartDelay(100)
            .rotationX()
            .setDuration(200)
            .setInterpolator(new DecelerateInterpolator())
            .setListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {
                }

                @Override
                public void onAnimationEnd(Animator animation) {

                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            }).start();

根据你的xml还有其他一些方法:

// scale animation
ScaleAnimation scaleanim = new ScaleAnimation(float fromX, float toX, float fromY, float toY);
scaleanim.setDuration(500);

// create translation animation
TranslateAnimation translateanim = new TranslateAnimation(0, 0,
        TranslateAnimation.ABSOLUTE, xTo - getLeft(), 0, 0,
        TranslateAnimation.ABSOLUTE, yTo - getTop());
translateanim.setDuration(700);

您可以使用RotateAnimationAlphaAnimation等尝试使用它们,如果您失败或提供更具体的帮助,我会向您提供我现有项目的代码。

@Edit:示例TranslateAnimation构造函数:

Animation animation = new TranslateAnimation(
float fromXDelta, float toXDelta, float fromYDelta, float toYDelta);
animation.setDuration(1500);
animation.setFillAfter(true);
view.startAnimation(animation);