android 自定义进度条控件
时间: 2023-09-26 17:11:10 浏览: 79
Android中自定义进度条控件可以通过继承ProgressBar来实现。以下是一个示例代码:
```
public class CustomProgressBar extends ProgressBar {
private Paint paint;
private RectF rectF;
public CustomProgressBar(Context context) {
super(context);
init();
}
public CustomProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomProgressBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.BLUE);
rectF = new RectF();
}
@Override
protected synchronized void onDraw(Canvas canvas) {
super.onDraw(canvas);
rectF.left = getPaddingLeft();
rectF.top = getPaddingTop();
rectF.right = getWidth() - getPaddingRight();
rectF.bottom = getHeight() - getPaddingBottom();
float progress = (float) getProgress() / (float) getMax();
float secondaryProgress = (float) getSecondaryProgress() / (float) getMax();
canvas.drawRoundRect(rectF, 10, 10, paint); // 绘制背景
canvas.drawRoundRect(rectF.left, rectF.top, rectF.right * progress, rectF.bottom, 10, 10, paint); // 绘制进度条
canvas.drawRoundRect(rectF.left, rectF.top, rectF.right * secondaryProgress, rectF.bottom, 10, 10, paint); // 绘制第二进度条
}
}
```
以上代码绘制了一个圆角矩形的进度条,可以自定义颜色、圆角大小等属性。在布局文件中引用该控件即可:
```
<com.example.CustomProgressBar
android:id="@+id/progress_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="50"
android:secondaryProgress="75" />
```
阅读全文