【安卓基础】简单快捷的加载中对话框

遇到的需求

  • 项目中有些界面需要显示加载中,例如登陆界面、注册界面等等。一开始考虑找个第三方库,但是第三方库往往为了达到普遍的适用性,封装得非常复杂。有时候一个库就差不多1mb大小,这样接入成本太大了,况且一个项目还需要其他第三方库接入,如果每一个功能都用第三方库解决,势必导致开发出来的应用体积臃肿,而且难以管理结构。
  • 而我只是需要简单展示一个加载中提示,所以自己实现一个会更加合理,而且更加小巧灵活。

 

方案的选择

在安卓开发中,系统提供了对话框类用于开发。所以我直接选择使用Support V7的AlertDialog作为实现方案。

  • AlertDialog继承自AppCompatDialog,使用方法与Dialog无差别,他在低版本安卓上也能显示谷歌最新的设计规范。
  • 通常使用AlertDialog都是通过Builder进行构造,Builder可以设置对话框的相关属性(标题、内容、监听器等等)。

 

实现分析

因为只是需要简单展示加载中的图标,图标有动画不停地旋转,当对话框显示地时候,全屏附带半透明灰色的背景。这些需求总结出来实现的思路如下:

  1. AlertDialog创建完之后,通过getWindow().setBackgroundDrawable()将默认的白色背景色去掉。
  2. dialog.getWindow().setDimAmount(0.8f),设置对话框后一层的暗淡程度,默认可以不设置。
  3. builder.setView(view),设置自定义内容,自定义的View从布局加载,有一个居中的ImageView。
  4. 对话框显示的时候,使用动画将ImageView不停旋转,达到加载中的显示效果。
  5. 设计两个API接口以供使用对话框:showLoading(Context)、releaseLoading(Context)

 

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>

 

知识点总结

  1. AlertDialog对话框的使用(设置背景、控制暗淡程度、自定义内容)
  2. RotateAnimation动画的使用(绕中心旋转、动画插值器)

相关文章