点击Extended FloatingActionButton时如何实现背景模糊效果?
先解决监听方法找不到的问题
你提到的setOnMenuToggleListener和setOnFloatingActionsMenuUpdateListener是**FloatingActionsMenu组件**的专属方法,不属于ExtendedFloatingActionButton。如果你的需求是点击主按钮展开子菜单,需要用FloatingActionsMenu作为容器,将ExtendedFloatingActionButton设为主按钮,再嵌套子FAB。
实现背景模糊的两种方案
方案一:Android 12+ 原生RenderEffect实现(推荐)
利用Android 12新增的RenderEffect实现高效模糊,步骤如下:
布局添加全屏模糊层:
在XML最上层添加一个覆盖全屏的View,初始隐藏:<View android:id="@+id/blur_view" android:layout_width="match_parent" android:layout_height="match_parent" android:visibility="gone" android:background="@color/black_40" /> <!-- 半透明黑底增强模糊层次感 --> <!-- 用FloatingActionsMenu包裹主ExtendedFAB和子按钮 --> <com.google.android.material.floatingactionbutton.FloatingActionsMenu android:id="@+id/fab_menu" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|end" android:layout_margin="16dp" app:fabCradleRoundedCornerRadius="16dp"> <com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton android:id="@+id/main_extended_fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="新建" app:icon="@drawable/ic_add" /> <!-- 子FAB示例 --> <com.google.android.material.floatingactionbutton.FloatingActionButton android:id="@+id/sub_fab_photo" android:layout_width="wrap_content" android:layout_height="wrap_content" app:icon="@drawable/ic_camera" /> </com.google.android.material.floatingactionbutton.FloatingActionsMenu>代码中设置监听和模糊逻辑:
val blurView = findViewById<View>(R.id.blur_view) val fabMenu = findViewById<FloatingActionsMenu>(R.id.fab_menu) // 监听菜单展开/收起状态 fabMenu.setOnMenuToggleListener { isExpanded -> if (isExpanded) { // 创建模糊效果,参数为X/Y方向模糊半径,瓦片模式 val blurEffect = RenderEffect.createBlurEffect(12f, 12f, Shader.TileMode.CLAMP) blurView.setRenderEffect(blurEffect) blurView.visibility = View.VISIBLE } else { blurView.visibility = View.GONE blurView.setRenderEffect(null) // 清除模糊 } }
方案二:兼容低版本(Android 12以下)
如果需要兼容更低版本,可以使用自定义模糊实现或成熟的模糊库:
添加依赖(以常用的模糊库为例):
在模块级build.gradle中添加:implementation 'com.github.Dimezis:BlurView:2.0.3'替换布局中的模糊View:
<com.jackandphantom.blurview.BlurView android:id="@+id/blur_view" android:layout_width="match_parent" android:layout_height="match_parent" android:visibility="gone" app:blurRadius="12" app:blurOverlayColor="@color/black_40" />代码中初始化并控制显示:
val blurView = findViewById<BlurView>(R.id.blur_view) val fabMenu = findViewById<FloatingActionsMenu>(R.id.fab_menu) // 初始化模糊View,设置要模糊的背景根布局 val rootView = window.decorView.findViewById<View>(android.R.id.content) blurView.setupWith(rootView) .setFrameClearDrawable(rootView.background) fabMenu.setOnMenuToggleListener { isExpanded -> blurView.visibility = if (isExpanded) View.VISIBLE else View.GONE }
单个ExtendedFAB的模糊逻辑
如果只是点击单个ExtendedFloatingActionButton时触发背景模糊(不需要子菜单),直接给按钮加点击监听:
val extendedFab = findViewById<ExtendedFloatingActionButton>(R.id.extended_fab) extendedFab.setOnClickListener { // 切换模糊层显示/隐藏,模糊逻辑同上述方案 }
内容的提问来源于stack exchange,提问作者Kate
相关产品推荐
相关产品推荐

