如何让锚定在BottomSheet上的FAB始终保持顶部位置并保留边距?
解决FAB锚定BottomSheet后底部边距失效的问题
我之前也碰到过一模一样的坑!当你用app:layout_anchor把FAB锚定到BottomSheet时,CoordinatorLayout的内置Behavior会完全接管FAB的位置计算,这时候你设置的layout_marginBottom(相对于父布局底部的边距)就会被直接忽略——因为FAB的位置现在是跟着BottomSheet的锚点走的,不再参考父布局的边界。
快速修复方案
你只需要做两个小改动就能搞定:
- 移除FAB的
android:layout_marginBottom属性:这个属性在锚定模式下完全不起作用,留着反而会混淆布局逻辑。 - 用
android:translationY设置FAB与BottomSheet顶部的间距:给FAB添加一个负的translationY值,让它向上偏移,保持和BottomSheet顶部的固定距离。比如你原本想留76dp的间距,就设置android:translationY="-76dp"。
修改后的FAB代码如下:
<com.google.android.material.floatingactionbutton.FloatingActionButton android:id="@+id/floatingActionButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="16dp" android:layout_marginRight="16dp" android:clickable="true" android:focusable="true" android:translationY="-76dp" <!-- 新增这个属性,替换原来的marginBottom --> app:layout_anchor="@+id/bottomSheet" app:layout_anchorGravity="top|end" app:srcCompat="@drawable/ic_covid" android:contentDescription="@string/verifica_gp" />
更优雅的布局方案(推荐)
如果你不想用translationY(毕竟它属于视图变换,不是纯布局属性),可以给BottomSheet的根布局添加顶部内边距,让FAB自然锚定到间距位置:
- 打开你的
bottom_sheet_pterm.xml,给根布局添加android:paddingTop="76dp"。 - 保持FAB的
app:layout_anchor="@+id/bottomSheet"和app:layout_anchorGravity="top|end"不变,移除layout_marginBottom。
这样FAB就会自动定位在BottomSheet顶部的padding区域上方,不管BottomSheet展开还是收起,都能保持固定的间距,而且完全是通过布局属性实现的,更符合Android布局的规范。
为什么原来的方法失效?
再拆解下背后的逻辑:当你设置app:layout_anchor时,CoordinatorLayout会将FAB的位置与锚定View(这里是BottomSheet)绑定,FAB的位置计算会基于BottomSheet的边界,而不是父布局的边界。这时候layout_marginBottom是相对于父布局底部的边距,自然就被Behavior覆盖了——毕竟FAB现在是跟着BottomSheet走的,父布局的底部位置对它来说已经不重要了。
内容的提问来源于stack exchange,提问作者NiceToMytyuk
相关产品推荐
相关产品推荐

