使用ValueAnimator实现一个匀速的下拉动画
点击显示部分可以匀速的下拉出隐藏部分,再次点击隐藏部分匀速收回。
【Android 下拉展开动画】
public class DropTest extends Activity { private LinearLayout mHiddenView;
private float mDensity;
private int mHiddenViewMeasuredHeight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drop);
mHiddenView = (LinearLayout) findViewById(R.id.hidden_view);
// 获取像素密度
mDensity = getResources().getDisplayMetrics().density;
// 获取布局的高度
mHiddenViewMeasuredHeight = (int) (mDensity * 40 + 0.5);
} public void llClick(View view) {
if (mHiddenView.getVisibility() == View.GONE) {
// 打开动画
animateOpen(mHiddenView);
} else {
// 关闭动画
animateClose(mHiddenView);
}
} @SuppressLint("NewApi")
private void animateOpen(final View view) {
view.setVisibility(View.VISIBLE);
ValueAnimator animator = createDropAnimator(view, 0,
mHiddenViewMeasuredHeight);
animator.start();
} @SuppressLint("NewApi")
private void animateClose(final View view) {
int origHeight = view.getHeight();
ValueAnimator animator = createDropAnimator(view, origHeight, 0);
animator.addListener(new AnimatorListenerAdapter() {
public void onAnimationEnd(Animator animation) {
// 动画结束时隐藏view
view.setVisibility(View.GONE);
}
});
animator.start();
} @SuppressLint("NewApi")
private ValueAnimator createDropAnimator(final View view, int start, int end) {
// 创建一个数值发生器
ValueAnimator animator = ValueAnimator.ofInt(start, end);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
int value = https://www.it610.com/article/(Integer) valueAnimator.getAnimatedValue();
ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
layoutParams.height = value;
view.setLayoutParams(layoutParams);
}
});
return animator;
}
}