Android examples for Animation:Collapse Animation
Validate view visibility status and execute the proper animation to expand or collapse
import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.Transformation; public class Main{ public static final void horizontalExpandTranformation(View viewValue) { if (viewValue.getVisibility() == View.VISIBLE) { AnimationUtils.horizontalCollapse(viewValue); } else {//from ww w . java 2s . co m AnimationUtils.horizontalExpand(viewValue); } } public static void horizontalCollapse(final View viewValue) { if (viewValue.getVisibility() == View.GONE) { return; } final int initialWidth = viewValue.getMeasuredWidth(); Animation animation = new Animation() { @Override protected void applyTransformation(float interpolatedTime, Transformation transformation) { if (interpolatedTime == 1) { viewValue.setVisibility(View.GONE); } else { viewValue.getLayoutParams().width = initialWidth - (int) (initialWidth * interpolatedTime); viewValue.requestLayout(); } } @Override public boolean willChangeBounds() { return true; } }; animation.setDuration((int) (initialWidth / viewValue.getContext() .getResources().getDisplayMetrics().density)); viewValue.startAnimation(animation); } public static void horizontalExpand(final View viewValue) { if (viewValue.getVisibility() == View.VISIBLE) { return; } viewValue.measure(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); final int targetWidth = viewValue.getMeasuredWidth(); viewValue.getLayoutParams().width = 0; viewValue.setVisibility(View.VISIBLE); Animation animation = new Animation() { @Override protected void applyTransformation(float interpolatedTime, Transformation transformation) { viewValue.getLayoutParams().width = interpolatedTime == 1 ? ViewGroup.LayoutParams.WRAP_CONTENT : (int) (targetWidth * interpolatedTime); viewValue.requestLayout(); } @Override public boolean willChangeBounds() { return true; } }; animation.setDuration((int) (targetWidth / viewValue.getContext() .getResources().getDisplayMetrics().density)); viewValue.startAnimation(animation); } }