帮我写一个Android自定义View进度条,进度条颜色是渐变色,宽高可以自行设置
时间: 2023-04-10 21:02:31 浏览: 185
好的,以下是一个简单的 Android 自定义 View 进度条的代码,进度条颜色为渐变色,宽高可以自行设置:
```java
public class GradientProgressBar extends View {
private Paint mPaint;
private int mWidth;
private int mHeight;
private int mProgress;
private int mMaxProgress;
private int[] mColors;
public GradientProgressBar(Context context) {
this(context, null);
}
public GradientProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStyle(Paint.Style.FILL);
mColors = new int[]{Color.RED, Color.YELLOW, Color.GREEN};
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
mWidth = MeasureSpec.getSize(widthMeasureSpec);
mHeight = MeasureSpec.getSize(heightMeasureSpec);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float progressWidth = (float) mProgress / mMaxProgress * mWidth;
LinearGradient gradient = new LinearGradient(0, 0, progressWidth, mHeight, mColors, null, Shader.TileMode.CLAMP);
mPaint.setShader(gradient);
canvas.drawRect(0, 0, progressWidth, mHeight, mPaint);
}
public void setProgress(int progress) {
mProgress = progress;
invalidate();
}
public void setMaxProgress(int maxProgress) {
mMaxProgress = maxProgress;
}
public void setColors(int[] colors) {
mColors = colors;
}
}
```
你可以在布局文件中使用这个自定义 View,例如:
```xml
<com.example.GradientProgressBar
android:id="@+id/progress_bar"
android:layout_width="match_parent"
android:layout_height="10dp"
app:colors="@array/progress_colors"
app:maxProgress="100"
app:progress="50" />
```
其中,`colors` 属性是一个颜色数组,`maxProgress` 属性是最大进度值,`progress` 属性是当前进度值。
阅读全文