android 自定义动画 水平进度条怎么实现
时间: 2023-09-15 17:24:33 浏览: 70
在 Android 中实现水平进度条动画,可以通过自定义 View 来实现。以下是实现的步骤:
1. 创建自定义 View 类,继承自 View。
2. 在 View 中添加一个属性,表示进度值,例如 progress。
3. 在 View 的 onDraw 方法中绘制进度条背景和进度条前景。
4. 在 View 中增加一个动画,可以使用 ValueAnimator 或 ObjectAnimator 类来实现。在动画更新的时候,设置进度值,并调用 invalidate 方法来触发 View 的重绘。
5. 在使用该自定义 View 的 Activity 或 Fragment 中,调用 View 的 startAnimation 方法来开始动画。
以下是一个简单的示例代码:
```
public class HorizontalProgressBar extends View {
private int progress = 0;
private Paint bgPaint, fgPaint;
private ValueAnimator animator;
public HorizontalProgressBar(Context context) {
super(context);
init();
}
public HorizontalProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
bgPaint = new Paint();
bgPaint.setColor(Color.GRAY);
fgPaint = new Paint();
fgPaint.setColor(Color.BLUE);
animator = ValueAnimator.ofInt(0, 100);
animator.setDuration(1000);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
progress = (int) animation.getAnimatedValue();
invalidate();
}
});
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = getWidth();
int height = getHeight();
canvas.drawRect(0, 0, width, height, bgPaint);
canvas.drawRect(0, 0, width * progress / 100, height, fgPaint);
}
public void startAnimation() {
animator.start();
}
}
```
在使用时,只需要将该自定义 View 添加到布局文件中,并在 Activity 或 Fragment 中调用 startAnimation 方法即可:
```
HorizontalProgressBar progressBar = findViewById(R.id.progress_bar);
progressBar.startAnimation();
```