Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 695
MichelReap Avatar asked Nov 04 '13 10:11

MichelReap


People also ask

How do you show and hide a view with a slide up down animation Android?

In android, we simply hide a view by setting its visibility. We can do this either in programming or in xml. In programming (we can say in Activity, Fragment etc) there is setVisibility(int) method to set or control the visibility of the view.

What is animateLayoutChanges?

Recently, I have discovered a new one regarding android:animateLayoutChanges . For those unfamiliar with this XML attribute, it's a “automagical” way to animate changes in your ViewGroups. This has been around since API 11 aka Honeycomb.


1 Answers

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);         }     }); 
like image 169
Xaver Kapeller Avatar answered Sep 24 '22 14:09

Xaver Kapeller