Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly animate stacking views one after another in Android using handler?

I have a LinearLayout with RelativeLayout children. Each RelativeLayout has a background image like a file cabinet. I am trying to animate the drawers dropping down into view one after another with a smooth delay. Everything I have tried plays all animations at once. I have this as my method for animating each drawer:

    private void dropAndPause(final RelativeLayout drawer){
    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            animation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.slide_down);
            animation.setStartOffset(750L);
            drawer.startAnimation(animation);
        }
    }, 1200);
}

I have also tried this:

    View[] views = new View[] { ... };

// 100ms delay between Animations
long delayBetweenAnimations = 100l; 

for(int i = 0; i < views.length; i++) {
    final View view = views[i];

    // We calculate the delay for this Animation, each animation starts 100ms 
    // after the previous one
    int delay = i * delayBetweenAnimations;

    view.postDelayed(new Runnable() {
        @Override
        public void run() {
            Animation animation = AnimationUtils.loadAnimation(context, R.anim.your_animation);    
            view.startAnimation(animation);
        }
    }, delay);
}

Instead of View[] views, I used this:

    View[] drawers = new View[] {
    drawerOne, drawerTwo, drawerThree, drawerFour, drawerFive
};

Which plays, again, all of the animations at once. How can I get each "drawer"/view to slide in one at a time? Also, should I have each view as visibility GONE initially?

like image 222
Steve C. Avatar asked Dec 05 '25 11:12

Steve C.


1 Answers

If you want to animate the views inside a layout, then it's much easier to use layout animations. Basically, you need to load an animation, create a LayoutAnimationController, set the delay on it, and launch the animation. Here's some sample code.

Animation animation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.slide_down);
animation.setStartOffset(750L);

LayoutAnimationController controller = new LayoutAnimationController(animation);
controller.setDelay(0.1F);

viewGroup.setLayoutAnimation(controller);
viewGroup.startLayoutAnimation();

The delay here is set as fraction of the animation duration.

like image 65
Malcolm Avatar answered Dec 06 '25 23:12

Malcolm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!