Skip to content

Instantly share code, notes, and snippets.

@akshaydashrath
Last active April 17, 2016 09:42
Show Gist options
  • Save akshaydashrath/636bb2ed9e82930942a27fbd55119e40 to your computer and use it in GitHub Desktop.
Save akshaydashrath/636bb2ed9e82930942a27fbd55119e40 to your computer and use it in GitHub Desktop.
Collapse and expand a view on Android with a clean animation
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Transformation;
public class ViewVisibilityAnimator {
private static final String VISIBILITY = "VISIBILITY";
public ViewVisibilityAnimator() {
}
public void saveState(View view, Bundle bundle) {
if (bundle == null) {
return;
}
bundle.putInt(VISIBILITY, view.getVisibility());
}
public void restoreState(View view, Bundle bundle) {
if (bundle == null) {
return;
}
view.setVisibility(bundle.getInt(VISIBILITY));
}
public void toggle(View view) {
if (view.getVisibility() == View.VISIBLE) {
collapse(view);
return;
}
expand(view);
}
public void expand(final View v) {
v.measure(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
final int targtetHeight = v.getMeasuredHeight();
v.getLayoutParams().height = 0;
v.setVisibility(View.VISIBLE);
Animation a = new Animation() {
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
v.getLayoutParams().height = interpolatedTime == 1 ? ViewGroup.LayoutParams.WRAP_CONTENT : (int) (targtetHeight * interpolatedTime);
v.requestLayout();
}
@Override
public boolean willChangeBounds() {
return true;
}
};
a.setDuration((int) (targtetHeight / v.getContext().getResources().getDisplayMetrics().density));
v.startAnimation(a);
}
public void collapse(final View v) {
final int initialHeight = v.getMeasuredHeight();
Animation a = new Animation() {
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
if (interpolatedTime == 1) {
v.setVisibility(View.GONE);
} else {
v.getLayoutParams().height = initialHeight - (int) (initialHeight * interpolatedTime);
v.requestLayout();
}
}
@Override
public boolean willChangeBounds() {
return true;
}
};
a.setDuration((int) (initialHeight / v.getContext().getResources().getDisplayMetrics().density));
v.startAnimation(a);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment