使用ValueAnimator可以做一些很骚的操作,比如实现一个进度条。实现的原理很简单,利用ValueAnimator的onAnimationUpdate,均匀的从0-1变化,我们在回调中动态设置View的宽度,实现轻量的进度条。我的需求是一个循环的进度条,代码如下:
private void startAnimator(View view) {
// 创建一个属性动画
mValueAnimator = ValueAnimator.ofFloat(0, 1.0f);
WindowManager wm = (WindowManager) mContext
.getSystemService(Context.WINDOW_SERVICE);
int width = wm.getDefaultDisplay().getWidth();
mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
Float progress = (Float) animation.getAnimatedValue();
ViewGroup.LayoutParams params = view.getLayoutParams();
params.width = (int) (progress * width);
view.setLayoutParams(params);
view.setVisibility(View.VISIBLE);
}
});
// 持续时长
mValueAnimator.setDuration(6000);
mValueAnimator.setInterpolator(new LinearInterpolator());
mValueAnimator.setRepeatCount(ValueAnimator.INFINITE);
// 播放
mValueAnimator.start();
}
|