在安卓App项目中,经常会遇到点击一个View展开,再次点击收起。
如果选择用 View.VISIBLE 和 View.GONE的话,会显得很突兀,用户体验不流畅,于是我们就想要制作一个平滑展开和收起的View。
效果图如下:
平滑展开收起.gif
在这里,我写了一个工具类,来操作View的展开和收起的效果。
核心代码:
public class ViewAnimationUtils {
public static void expand(View view, int maxHeight) {
DropAnim.getInstance().animateOpen(view, maxHeight);
}
public static void collapse(View view) {
DropAnim.getInstance().animateClose(view);
}
}
其中,DropAnim是View平滑显示和收起的动画。
DropAnim
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.view.View;
import android.view.ViewGroup;
public class DropAnim {
private static DropAnim dropAnim;
public static DropAnim getInstance() {
if (dropAnim == null) {
dropAnim = new DropAnim();
}
return dropAnim;
}
public void animateOpen(View v,int mHiddenViewMeasuredHeight) {
v.setVisibility(View.VISIBLE);
ValueAnimator animator = createDropAnimator(v, 0,
mHiddenViewMeasuredHeight);
animator.start();
}
public void animateClose(final View view) {
int origHeight = view.getHeight();
ValueAnimator animator = createDropAnimator(view, origHeight, 0);
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
view.setVisibility(View.GONE);
}
});
animator.start();
}
public ValueAnimator createDropAnimator(final View v, int start, int end) {
ValueAnimator animator = ValueAnimator.ofInt(start, end);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator arg0) {
int value = (int) arg0.getAnimatedValue();
ViewGroup.LayoutParams layoutParams = v.getLayoutParams();
layoutParams.height = value;
v.setLayoutParams(layoutParams);
}
});
return animator;
}
}
网友评论