需求分析
想要底部导航栏实现BottomAppBar这种FAB的嵌入效果,但发现BottomAppBar不适合直接拿来做导航栏,如何用BottomNavigate的功能实现BottomAppBar的效果?
理论分析
在material design3中存在z轴,理论上只要将FAB的z轴高度高于BottomNavigateView,并将BottomNavigateView的背景设置为透明的就可以实现,并且不会遮挡FAB(仅适用于导航栏中图标为偶数的情况)。
实践
xml代码
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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=".MainActivity">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0">
<com.google.android.material.bottomappbar.BottomAppBar
android:id="@+id/bottomAppBar"
style="@style/Widget.MaterialComponents.BottomAppBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
app:elevation="8dp"
app:fabAlignmentMode="center"
app:fabAnimationMode="slide"
app:fabCradleMargin="8dp"
app:fabCradleRoundedCornerRadius="15dp"
app:fabCradleVerticalOffset="5dp"
app:hideOnScroll="true" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bn_menu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="@android:color/transparent"
app:elevation="0dp"
app:labelVisibilityMode="labeled"
app:layout_anchor="@+id/bottomAppBar"
app:layout_anchorGravity="center"
app:itemTextColor="@color/black"
app:itemIconTint="@color/black"
app:menu="@menu/top_menu_main" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/add_que"
app:elevation="12dp"
app:fabSize="normal"
app:layout_anchor="@id/bottomAppBar" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
效果如下:
中途遇到的问题
BottomNavigateView的app:elevation属性一定得设置成0dp,否则会出现下面这种情况
具体为什么会这样我也不太清楚,希望如果有幸被哪位大神看到可以解答我的疑惑。