You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何设置FloatingActionButton悬浮在BottomNavigationView上方

解决FloatingActionButton与BottomNavigationView位置重叠问题

问题原因

你当前的布局里,FloatingActionButton和包裹BottomNavigationView的ConstraintLayout都是CoordinatorLayout的直接子View,且都设置了底部对齐。加上ConstraintLayout在代码中位于FloatingActionButton之后,绘制时会覆盖FAB下半部分,视觉上就显得两者处于同一位置。另外,用ConstraintLayout包裹BottomNavigationView属于冗余布局,完全可以简化。

修复方案

利用CoordinatorLayout的锚定特性,让FAB直接锚定在BottomNavigationView上,系统会自动处理位置关系,同时简化布局结构:

修改后的完整布局代码:

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity2">

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/mobile_navigation" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        app:menu="@menu/bottom_menu" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginBottom="8dp"
        android:src="@drawable/ic_baseline_addchart_24"
        app:layout_anchor="@id/bottom_bar"
        app:layout_anchorGravity="end|top" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

关键修改点

  • 移除包裹BottomNavigationView的冗余ConstraintLayout,直接将BottomNavigationView作为CoordinatorLayout的子View,设置layout_gravity="bottom"实现底部对齐。
  • 给FloatingActionButton添加app:layout_anchor="@id/bottom_bar"指定锚定目标为底部导航栏,再通过app:layout_anchorGravity="end|top"设置FAB锚定在导航栏的右上角顶部位置。
  • 调整FAB的margin,让它和导航栏保持合适间距,避免视觉拥挤。

内容的提问来源于stack exchange,提问作者Serg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 00:01:40