× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Android adding simple animations while setvisibility(view.Gone)

Xaver Kapeller
Mar 13, 2015
<p>You can do two things to add animations, first you can let android animate layout changes for you. That way every time you change something in the layout like changing view visibility or view positions android will automatically create fade/transition animations. To use that set </p> <pre><code>android:animateLayoutChanges="true" </code></pre> <p>on the root node in your layout.</p> <p>Your second option would be to manually add animations. For this I suggest you use the new animation API introduced in Android 3.0 (Honeycomb). I can give you a few examples:</p> <p>This fades out a <code>View</code>:</p> <pre><code>view.animate().alpha(0.0f); </code></pre> <p>This fades it back in:</p> <pre><code>view.animate().alpha(1.0f); </code></pre> <p>This moves a <code>View</code> down by its height:</p> <pre><code>view.animate().translationY(view.getHeight()); </code></pre> <p>This returns the <code>View</code> to its starting position after it has been moved somewhere else:</p> <pre><code>view.animate().translationY(view.getHeight()); </code></pre> <p>You can also use <code>setDuration()</code> to set the duration of the animation. For example this fades out a <code>View</code> over a period of 2 seconds:</p> <pre><code>view.animate().alpha(0.0f).setDuration(2000); </code></pre> <p>And you can combine as many animations as you like, for example this fades out a <code>View</code> and moves it down at the same time over a period of 0.3 seconds:</p> <pre><code>view.animate() .translationY(view.getHeight()) .alpha(0.0f) .setDuration(300); </code></pre> <p>And you can also assign a listener to the animation and react to all kinds of events. Like when the animation starts, when it ends or repeats etc. By using the abstract class <code>AnimatorListenerAdapter</code> you don't have to implement all callbacks of <code>AnimatorListener</code> at once but only those you need. This makes the code more readable. For example the following code fades out a <code>View</code> moves it down by its height over a period of 0.3 seconds (300 milliseconds) and when the animation is done its visibility is set to <code>View.GONE</code>.</p> <pre><code>view.animate() .translationY(view.getHeight()) .alpha(0.0f) .setDuration(300) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); view.setVisibility(View.GONE); } }); </code></pre> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/22454839/Android%20adding%20simple%20animations%20while%20setvisibility(view.Gone)/22454966">Stack Overflow</a>.</p>
comments powered by Disqus