在Android開發中,ProgressDrawable是一個用于表示加載進度的可繪制對象
首先,我們需要創建一個自定義的ProgressDrawable。這可以通過繼承ProgressDrawable類并重寫其方法來實現。例如,我們可以創建一個名為CustomProgressDrawable的類:
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.SystemClock;
public class CustomProgressDrawable extends Drawable {
private Paint paint;
private int progress;
public CustomProgressDrawable() {
paint = new Paint();
paint.setColor(0xFF009688);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(10);
}
@Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
}
@Override
public void draw(Canvas canvas) {
Rect bounds = getBounds();
int width = bounds.width();
int height = bounds.height();
int startAngle = -90;
int sweepAngle = (int) (360 * (progress / 100f));
canvas.drawArc(bounds.left, bounds.top, bounds.right, bounds.bottom, startAngle, sweepAngle, false, paint);
}
@Override
public void setAlpha(int alpha) {
paint.setAlpha(alpha);
}
@Override
public void setColorFilter(ColorFilter colorFilter) {
paint.setColorFilter(colorFilter);
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
public void setProgress(int progress) {
this.progress = progress;
invalidateSelf();
}
}
接下來,我們需要將自定義的ProgressDrawable應用到一個View上。例如,我們可以將其應用到一個ImageView上:
android:id="@+id/imageView"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@drawable/ic_launcher_background" />
在Activity或Fragment中,我們可以將自定義的ProgressDrawable設置為ImageView的Drawable:
ImageView imageView = findViewById(R.id.imageView);
CustomProgressDrawable customProgressDrawable = new CustomProgressDrawable();
imageView.setImageDrawable(customProgressDrawable);
為了展示ProgressDrawable的動畫效果,我們可以使用一個線程或Handler來更新其進度。例如,我們可以使用Handler來實現:
private Handler handler = new Handler();
private Runnable updateProgressRunnable = new Runnable() {
@Override
public void run() {
if (customProgressDrawable != null) {
int progress = customProgressDrawable.getProgress();
if (progress < 100) {
customProgressDrawable.setProgress(progress + 1);
handler.postDelayed(this, 50);
} else {
customProgressDrawable.setProgress(0);
handler.postDelayed(this, 50);
}
}
}
};
在適當的時候(例如,在Activity的onCreate方法中),我們可以啟動這個Runnable:
handler.post(updateProgressRunnable);
這樣,我們就創建了一個自定義的ProgressDrawable,并將其應用到了一個ImageView上。通過不斷更新ProgressDrawable的進度,我們可以實現一個簡單的加載動畫效果。