在Android中使用XML布局创建弧形进度条,而不需要额外的库,可以通过自定义View来实现。以下是一个实现的示例:
public class ArcProgressBar extends View {
private Paint paint;
private RectF rectF;
private float progress;
public ArcProgressBar(Context context) {
super(context);
init();
}
public ArcProgressBar(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public ArcProgressBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(10);
paint.setColor(Color.BLUE);
rectF = new RectF();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float angle = 360 * progress / 100;
canvas.drawArc(rectF, -90, angle, false, paint);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
int size = Math.min(width, height);
rectF.set(10, 10, size - 10, size - 10);
setMeasuredDimension(size, size);
}
public void setProgress(float progress) {
this.progress = progress;
invalidate();
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<com.example.myapplication.ArcProgressBar
android:id="@+id/arcProgressBar"
android:layout_width="200dp"
android:layout_height="200dp" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
private ArcProgressBar arcProgressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
arcProgressBar = findViewById(R.id.arcProgressBar);
arcProgressBar.setProgress(50);
}
}
这样就可以在Android中使用XML布局创建一个简单的弧形进度条了。你可以根据需要自定义进度条的样式、颜色等。
领取专属 10元无门槛券
手把手带您无忧上云