Show and hide a View with a slide up/down animation

MichelReap picture MichelReap · Nov 4, 2013 · Viewed 378.5k times · Source

I have a LinearLayout that I want to show or hide with an Animation that pushes the layout upwards or downwards whenever I change its visibility.

I've seen a few samples out there but none of them suit my needs.

I have created two xml files for the animations but I do not know how to start them when I change the visibility of a LinearLayout.

Answer

Xaver Kapeller picture Xaver Kapeller · Nov 4, 2013

With the new animation API that was introduced in Android 3.0 (Honeycomb) it is very simple to create such animations.

Sliding a View down by a distance:

view.animate().translationY(distance);

You can later slide the View back to its original position like this:

view.animate().translationY(0);

You can also easily combine multiple animations. The following animation will slide a View down by its height and fade it in at the same time:

// Prepare the View for the animation
view.setVisibility(View.VISIBLE);
view.setAlpha(0.0f);

// Start the animation
view.animate()
    .translationY(view.getHeight())
    .alpha(1.0f)
    .setListener(null);

You can then fade the View back out and slide it back to its original position. We also set an AnimatorListener so we can set the visibility of the View back to GONE once the animation is finished:

view.animate()
    .translationY(0)
    .alpha(0.0f)
    .setListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            super.onAnimationEnd(animation);
            view.setVisibility(View.GONE);
        }
    });