在同一布局中启动两个动画

Geo*_*vik 6 android alpha android-linearlayout translate-animation

我试图做一个alpha并在RelativeLayout中翻译.我定义了两个:

AlphaAnimation alpha;
alpha = new AlphaAnimation(0.0f, 1.0f);
alpha.setDuration(1500);
alpha.setFillAfter(true);

TranslateAnimation translate;
translate = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0,                                                                       
                 Animation.RELATIVE_TO_SELF, 0,
                 Animation.RELATIVE_TO_SELF, 1, 
                 Animation.RELATIVE_TO_SELF, 0);
translate.setDuration(1000);
Run Code Online (Sandbox Code Playgroud)

所以我在RelativeLayout中启动动画

RelativeLayout.startAnimation(translate);
RelativeLayout.startAnimation(alpha);
Run Code Online (Sandbox Code Playgroud)

问题是在这种情况下,只有alpha动画开始而不是翻译.有人能帮我吗?问题是如何在同一个对象中同时启动两个不同的动画(在我的情况下为相对布局)


我解决了这个问题.我添加了它:

AnimationSet animationSet = new AnimationSet(true);
animationSet.addAnimation(alpha);
animationSet.addAnimation(translate);

RelativeLayout.startAnimation(animationSet);
Run Code Online (Sandbox Code Playgroud)

小智 7

你可以使用动画集ı如果你想在同一时间运行两个动画:

http://developer.android.com/reference/android/view/animation/AnimationSet.html

例如;

as = new AnimationSet(true);
as.setFillEnabled(true);
as.setInterpolator(new BounceInterpolator());

TranslateAnimation ta = new TranslateAnimation(-300, 100, 0, 0); 
ta.setDuration(2000);
as.addAnimation(ta);

TranslateAnimation ta2 = new TranslateAnimation(100, 0, 0, 0); 
ta2.setDuration(2000);
ta2.setStartOffset(2000); // allowing 2000 milliseconds for ta to finish
as.addAnimation(ta2);
Run Code Online (Sandbox Code Playgroud)


Kar*_*nan 5

您当前的代码将无法工作,因为第一个动画开始后,第二个动画结束并自行启动.所以你需要等到它完成.

试试这个 :

translate.setAnimationListener(new AnimationListener() {

    public void onAnimationStart(Animation animation) {
        // TODO Auto-generated method stub

    }

    public void onAnimationRepeat(Animation animation) {
        // TODO Auto-generated method stub

    }

    public void onAnimationEnd(Animation animation) {
        // TODO Auto-generated method stub
        RelativeLayout.startAnimation(alpha);
    }
});
Run Code Online (Sandbox Code Playgroud)

如果你想同时执行它们,我建议你在res/anim /文件夹中创建一个animation.xml文件.

例:

<?xml version="1.0" encoding="utf-8"?>
<set
 xmlns:android="http://schemas.android.com/apk/res/android">
<scale
android:fromXScale="1.0"
android:fromYScale="1.0"
 android:toXScale=".75"
 android:toYScale=".75"
 android:duration="1500"/>
<rotate
android:fromDegrees="0"
 android:toDegrees="360"
 android:duration="1500"
 android:pivotX="50%"
 android:pivotY="50%" />
<scale
android:fromXScale=".75"
 android:fromYScale=".75"
 android:toXScale="1"
 android:toYScale="1"
 android:duration="1500"/>
</set>
Run Code Online (Sandbox Code Playgroud)

Java代码:

 Animation multiAnim = AnimationUtils.loadAnimation(this, R.anim.animation);
    RelativeLayout.startAnimation(multiAnim);
Run Code Online (Sandbox Code Playgroud)