Android 自定义Loading现实动画
要实现自定义Loading动画,可以使用Android中的View动画或属性动画。
- View动画
View动画适用于简单的动画效果,比如逐帧动画或平移、旋转等基本动画。可以使用XML文件定义动画,然后通过代码加载并启动动画。
例如,可以创建一个名为loading_animation.xml的XML文件,定义一个旋转动画:
<rotate
xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:repeatCount="infinite"
android:duration="1000" />
然后在布局文件中添加一个ImageView控件,设置其src属性为一个Loading图片,同时设置scaleType为fitCenter,让图片居中显示:
<ImageView
android:id="@+id/loading_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="@drawable/loading"
android:scaleType="fitCenter"/>
最后在Activity中加载并启动动画:
Animation animation = AnimationUtils.loadAnimation(this, R.anim.loading_animation);
ImageView loadingImage = findViewById(R.id.loading_image);
loadingImage.startAnimation(animation);
这样就可以实现一个简单的旋转Loading动画。
- 属性动画
属性动画适用于复杂的动画效果,比如自定义路径动画或透明度动画等。属性动画允许对任何对象的任何属性进行动画操作。
例如,可以创建一个自定义LoadingView,继承自View,然后在其onDraw()方法中绘制一个圆形,并使用属性动画实现其旋转效果。
public class LoadingView extends View {
private float mAngle = 0;
public LoadingView(Context context) {
super(context);
init();
}
public LoadingView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public LoadingView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
// 设置一个周期为1秒的旋转动画
ObjectAnimator animator = ObjectAnimator.ofFloat(this, "angle", 0, 360);
animator.setDuration(1000);
animator.setInterpolator(new LinearInterpolator());
animator.setRepeatCount(ValueAnimator.INFINITE);
animator.start();
}
public void setAngle(float angle) {
mAngle = angle;
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int centerX = getWidth() / 2;
int centerY = getHeight() / 2;
int radius = Math.min(centerX, centerY) - 10;
Paint paint = new Paint();
paint.setColor(Color.parseColor("#FF4081"));
paint.setStyle(Paint.Style.FILL);
canvas.drawCircle(centerX, centerY, radius, paint);
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(5);
canvas.save();
canvas.rotate(mAngle, centerX, centerY);
canvas.drawCircle(centerX, centerY, radius, paint);
canvas.restore();
}
}
然后在布局文件中添加自定义的LoadingView:
<com.example.loadingview.LoadingView
android:id="@+id/loading_view"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_centerInParent="true"/>
这样就可以实现一个自定义的Loading动画,效果更加炫酷。
总结
以上就是Android自定义Loading动画的两种实现方式,View动画适用于简单的动画效果,属性动画适用于复杂的动画效果。开发者可以根据具体需求选择适合自己的方式
原文地址: https://www.cveoy.top/t/topic/ffko 著作权归作者所有。请勿转载和采集!