Android lottieAnimationView显示时调暗其余界面及AlertDialog实现代码咨询
实现方案
你猜测的用AlertDialog承载LottieAnimationView的方案是可行的,AlertDialog自带的半透明背景遮罩刚好能满足除目标控件外界面调暗的需求,弹窗消失时遮罩也会同步移除,不需要额外写全局调光逻辑。
1. 引入Lottie依赖(未引入的情况下)
在app模块的build.gradle(Module level)文件的dependencies块中添加依赖:
implementation "com.airbnb.android:lottie:6.4.0"
版本号可根据实际需求替换为最新稳定版。
2. 新建Lottie弹窗布局
在res/layout目录下新建布局文件dialog_lottie_loading.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@android:color/transparent" android:gravity="center" android:padding="24dp"> <com.airbnb.lottie.LottieAnimationView android:id="@+id/lottie_view" android:layout_width="120dp" android:layout_height="120dp" app:lottie_autoPlay="true" app:lottie_loop="true" app:lottie_rawRes="@raw/your_anim_file" /> <!-- 这里把your_anim_file替换为你自己的Lottie动画文件名,动画文件需提前放到res/raw目录下 --> </LinearLayout>
3. 弹窗调用逻辑
Kotlin版本(Activity中使用)
// 全局声明弹窗变量 private var lottieLoadingDialog: AlertDialog? = null // 显示Lottie弹窗(对应你需要Lottie可见的场景) private fun showLottieLoading() { if (lottieLoadingDialog == null) { val dialogView = layoutInflater.inflate(R.layout.dialog_lottie_loading, null) lottieLoadingDialog = AlertDialog.Builder(this) .setView(dialogView) .setCancelable(false) // 设为false则点击外部、返回键无法关闭弹窗,可按需调整 .create() // 移除弹窗默认白底 lottieLoadingDialog?.window?.setBackgroundDrawableResource(android.R.color.transparent) // 调整背景遮罩暗度,数值范围0-1,越大越暗,默认约0.5 lottieLoadingDialog?.window?.setDimAmount(0.7f) } lottieLoadingDialog?.show() } // 隐藏Lottie弹窗(对应你需要Lottie设为GONE的场景) private fun hideLottieLoading() { lottieLoadingDialog?.takeIf { it.isShowing }?.dismiss() } // 页面销毁时避免内存泄漏 override fun onDestroy() { super.onDestroy() lottieLoadingDialog?.dismiss() lottieLoadingDialog = null }
Java版本(Activity中使用)
// 全局声明弹窗变量 private AlertDialog lottieLoadingDialog; // 显示Lottie弹窗 private void showLottieLoading() { if (lottieLoadingDialog == null) { View dialogView = getLayoutInflater().inflate(R.layout.dialog_lottie_loading, null); lottieLoadingDialog = new AlertDialog.Builder(this) .setView(dialogView) .setCancelable(false) .create(); if (lottieLoadingDialog.getWindow() != null) { lottieLoadingDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent); lottieLoadingDialog.getWindow().setDimAmount(0.7f); } } lottieLoadingDialog.show(); } // 隐藏Lottie弹窗 private void hideLottieLoading() { if (lottieLoadingDialog != null && lottieLoadingDialog.isShowing()) { lottieLoadingDialog.dismiss(); } } // 页面销毁时回收 @Override protected void onDestroy() { super.onDestroy(); if (lottieLoadingDialog != null) { lottieLoadingDialog.dismiss(); lottieLoadingDialog = null; } }
需要显示Lottie时调用showLottieLoading(),需要隐藏时调用hideLottieLoading()即可。
内容的提问来源于stack exchange,提问作者aikagra
相关产品推荐
相关产品推荐

