Search code examples
androidandroid-linearlayoutalphatranslate-animation

Start two animation in the same Layout


Im trying to do an alpha and translate in a RelativeLayout. I define both:

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

So I start the animation in my RelativeLayout

RelativeLayout.startAnimation(translate);
RelativeLayout.startAnimation(alpha);

The problem is that in this case, only the alpha animation start and not the translation. Can someone help me? The question is how can I start two different animations at the same time in the same object(Relative Layout in my case)


I resolve the question. I added it:

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

RelativeLayout.startAnimation(animationSet);

Solution

  • Your current code won't work, because as soon as the first animation starts, the second one ends it and starts itself. So you need to wait till it's done.

    Try this :

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

    If you want to execute them simultaneously, I'd suggest you create an animation.xml file in your res/anim/ folder.

    Example:

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

    Java Code:

     Animation multiAnim = AnimationUtils.loadAnimation(this, R.anim.animation);
        RelativeLayout.startAnimation(multiAnim);