android自定义view实现水平进度条
时间: 2023-09-12 20:09:58 浏览: 80
好的,以下是实现水平进度条的自定义 View 的步骤:
1. 定义属性
在自定义 View 的类中定义属性,包括进度条的颜色、背景色、高度等等。
```java
public class HorizontalProgressBar extends View {
private int mProgressColor;
private int mBackgroundColor;
private int mHeight;
private int mMax;
private int mProgress;
...
}
```
2. 重写 onMeasure() 方法
在 onMeasure() 方法中,设置 View 的宽度和高度,以及默认值。
```java
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(width, mHeight);
if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY) {
height = MeasureSpec.getSize(heightMeasureSpec);
} else {
height = mHeight;
}
setMeasuredDimension(width, height);
}
```
3. 重写 onDraw() 方法
在 onDraw() 方法中,绘制进度条和背景。
```java
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float ratio = (float) mProgress / (float) mMax;
int progressWidth = (int) (getWidth() * ratio);
// 绘制背景
Paint bgPaint = new Paint();
bgPaint.setColor(mBackgroundColor);
canvas.drawRect(0, 0, getWidth(), getHeight(), bgPaint);
// 绘制进度
Paint progressPaint = new Paint();
progressPaint.setColor(mProgressColor);
canvas.drawRect(0, 0, progressWidth, getHeight(), progressPaint);
}
```
4. 设置属性
在自定义 View 的 XML 布局中设置属性,如下:
```xml
<com.example.customview.HorizontalProgressBar
android:id="@+id/horizontal_progress_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:progressColor="@color/colorPrimary"
app:backgroundColor="@color/gray"
app:height="5dp"
app:max="100"
app:progress="30" />
```
5. 在代码中使用
在代码中获取自定义 View,设置进度值。
```java
HorizontalProgressBar progressBar = findViewById(R.id.horizontal_progress_bar);
progressBar.setProgress(50);
```
以上就是实现水平进度条的自定义 View 的步骤。