在安卓开发中,系统提供了对话框类用于开发。所以我直接选择使用Support V7的AlertDialog作为实现方案。
因为只是需要简单展示加载中的图标,图标有动画不停地旋转,当对话框显示地时候,全屏附带半透明灰色的背景。这些需求总结出来实现的思路如下:
public class LoadingHelper { private static HashMap<Context, AlertDialog> mDialog = new HashMap<>(); public static void showLoading(Context context) { AlertDialog dialog = mDialog.get(context); if (dialog == null) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setCancelable(false); // 从布局加载View View root = LayoutInflater.from(context).inflate(R.layout.libs_loading_layout, null, false); builder.setView(root); // 启动动画不停旋转ImageView ImageView loadIcon = root.findViewById(R.id.uiLoadIcon); RotateAnimation animation = new RotateAnimation(0, -360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); animation.setRepeatCount(9999); animation.setDuration(3000); animation.setInterpolator(new LinearInterpolator()); loadIcon.startAnimation(animation); mDialog.put(context, dialog = builder.create()); // 背景设置 dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); dialog.getWindow().setDimAmount(0.1f); } dialog.show(); } public static void releaseLoading(Context context) { AlertDialog dialog = mDialog.get(context); if (dialog != null) { dialog.dismiss(); mDialog.remove(context); } }}
<?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@null"> <ImageView android:id="@+id/uiLoadIcon" android:layout_width="55dp" android:layout_height="55dp" android:src="@mipmap/lib_ic_loading" android:tint="#b2b2b2" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /></android.support.constraint.ConstraintLayout>