Android ExtendedFloatingActionButton调用shrink()方法无效果如何解决?
问题原因
- 你使用的Material 1.4.0版本存在已知BUG:当ExtendedFloatingActionButton设置了
app:layout_anchor锚点属性时,shrink()/extend()方法的动画逻辑会和CoordinatorLayout的锚点定位逻辑冲突,导致收缩操作被静默丢弃,不会触发回调也无视觉变化。 - 调用
shrink()的时机过早,此时组件还未完成布局测量、未附着到窗口,动画无法执行,操作直接被忽略。 - 未显式配置组件的初始展开状态,部分主题覆盖下组件默认初始状态就是收缩的,重复调用
shrink()不会触发任何回调。
解决方案
方案1:规避锚点冲突(优先推荐)
移除XML中ExtendedFloatingActionButton的app:layout_anchor和app:layout_anchorGravity属性,改用CoordinatorLayout常规布局规则定位按钮,同时显式添加app:expanded="true"明确初始展开状态:
<androidx.coordinatorlayout.widget.CoordinatorLayout ... > ... <com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton android:id="@+id/exploring_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|end" android:layout_marginEnd="16dp" android:layout_marginBottom="32dp" android:text="Start Exploring" app:icon="@drawable/ic_walking" app:expanded="true" /> </androidx.coordinatorlayout.widget.CoordinatorLayout>
如果需要跟随BottomSheet位移,可以监听BottomSheet的滑动回调动态调整按钮位置即可。
方案2:升级Material组件版本
该锚点冲突BUG在Material 1.5.0及以上版本已经被修复,可直接升级依赖版本:
implementation 'com.google.android.material:material:1.5.0' // 也可升级到更高稳定版,兼容性更好
升级后无需修改原有布局和业务代码,shrink()方法即可正常生效。
方案3:强制触发状态更新
如果暂时无法升级依赖也不想调整布局,可以在调用shrink()前先判断当前状态、强制刷新布局后再执行收缩:
Log.d(TAG, "shrinking start") if (binding.exploringBtn.isExtended) { binding.exploringBtn.requestLayout() binding.exploringBtn.shrink(object : ExtendedFloatingActionButton.OnChangedCallback() { override fun onShrunken(extendedFab: ExtendedFloatingActionButton?) { super.onShrunken(extendedFab) Log.d(TAG, "onShrunken: ") } override fun onExtended(extendedFab: ExtendedFloatingActionButton?) { super.onExtended(extendedFab) Log.d(TAG, "onExtended: ") } }) } Log.d(TAG, "shrinking end")
提前判断isExtended为true再执行收缩,避免无意义的重复调用。
内容的提问来源于stack exchange,提问作者Kes Walker
相关产品推荐
相关产品推荐

