要在Android ProgressBar上實現顏色漸變,您可以使用以下方法:
GradientProgressBar
的類并繼承ProgressBar
。import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.widget.ProgressBar;
public class GradientProgressBar extends ProgressBar {
private Paint paint;
private LinearGradient linearGradient;
public GradientProgressBar(Context context) {
super(context);
init();
}
public GradientProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public GradientProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
paint = new Paint();
paint.setAntiAlias(true);
linearGradient = new LinearGradient(0, 0, getWidth(), getHeight(), Color.RED, Color.BLUE, Shader.TileMode.CLAMP);
paint.setShader(linearGradient);
}
@Override
protected void onDraw(Canvas c) {
super.onDraw(c);
paint.setAlpha(getAlpha());
c.drawRect(0, 0, getWidth(), getHeight(), paint);
}
}
GradientProgressBar
。<your.package.name.GradientProgressBar
android:id="@+id/gradientProgressBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:indeterminate="false"
android:progress="50"/>
GradientProgressBar gradientProgressBar = findViewById(R.id.gradientProgressBar);
gradientProgressBar.setProgress(50); // 設置進度為50%
現在,您的進度條將具有從紅色到藍色的漸變顏色。您可以根據需要自定義漸變顏色和方向。