[Android MVVM 架构笔记] 基于 Kotlin 类委托与系统级安全扩展的全局 Loading 方案
在实际项目开发中,像“收藏、删除、分享、修改”这类由用户点击按钮触发的异步网络操作,在架构上被称为操作性动作(Action Operations)。
本方案遵循 “单一职责原则”、“组合优于继承” 以及 “编译期绝对安全” 的原则,将 Loading 业务完全从基类中剥离,利用 Kotlin类委托特性实现“按需插拔装载”,并通过系统原生组件级双重泛型约束,确保了极高的运行稳定性与代码优雅度 。
一、 完整物理文件清单与物理路径
布局文件:dialog_loading.xml 唯一样式 XML:毛玻璃质感加载卡片
包名/ui/widget:
LoadingDialogFragment.kt 弹窗组件:生命周期安全 DialogFragment
LoadingDelegateImpl.kt 契约实现:完全闭环的 Dialog 调度者 LoadingDelegate.kt 核心契约:Kotlin 风格加载委托接口
包名/util/ext:
ActivityExt.kt 系统级扩展:原生组件编译期安全响应式绑定
二、 完整源码实现
1. 唯一样式 XML:dialog_loading.xml
- 物理路径:app/src/main/res/layout/dialog_loading.xml
- 设计规范:采用 Material3 风格的 80% 半透明卡片,将整体 Loading 容器与具体页面布局 100% 解耦。
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.card.MaterialCardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
app:cardCornerRadius="12dp"
app:cardElevation="6dp"
app:cardBackgroundColor="#CCFFFFFF"> <!-- 80% 不透明度白色 -->
<com.google.android.material.progressindicator.CircularProgressIndicator
android:layout_width="wrap_content"
android:layout_h