在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的进度,我们可以实现一个简单的加载动画效果。