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
.
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.
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.
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); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With