/**
* @param v 传入需要收缩的布局(收缩动画)
*/
private void animClose(final View v) {
v.setVisibility(View.VISIBLE);
//layoutHeight是布局文件高度
ValueAnimator valueAnimator = createValueAnimator(v, layoutHeight, 0);
valueAnimator.setDuration(3000);
valueAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
v.setVisibility(View.GONE);
}
});
valueAnimator.start();
}
/**
* @param v 传入需要张开的布局(张开动画)
*/
private void animOpen(View v) {
v.setVisibility(View.VISIBLE);
//layoutHeight是布局文件高度
ValueAnimator valueAnimator = createValueAnimator(v, 0, layoutHeight);
valueAnimator.setDuration(3000);
valueAnimator.start();
}
/**
* @param v 需要展开收缩的布局控件
* @param start 开始位置
* @param end 结束位置
* @return 返回 ValueAnimator属性动画对象
*/
private ValueAnimator createValueAnimator(final View v, int start, int end) {
ValueAnimator valueAnimator = ValueAnimator.ofInt(start, end);
valueAnimator.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
int value = (int) animation.getAnimatedValue();
ViewGroup.LayoutParams layoutParams = v.getLayoutParams();
layoutParams.height = value;
v.setLayoutParams(layoutParams);
}
});
return valueAnimator;
}
其中的layoutHeight高度在onCreate()方法中使用
layoutHeight=view.getHeight();或
layoutHeight=view.getMeasuredHeight();
是获取不到布局的高度的,打印出的layoutHeight为0;
在onCreate()方法中获取布局的宽高可以使用以下方法:
int w=View.MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
int h=View.MeasureSpec.makeMeasureSpec(0,MeasureSpec.UNSPECIFIED);
view.measure(w, h);
int width=view.getMeasuredWidth();
int height=view.getMeasuredHeight();