您應該使用片段而不是活動。只有1個活動,即MainActivity,在BottomNavigationView上添加BottomNavigationView和片段。在點擊BottomNavigationView時,替換碎片。 您的XML會是這樣的,
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">
<View
android:id="@+id/bottom_nav_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"/>
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_above="@id/bottom_nav_view"></FrameLayout>
從你的活動中,FrameLayout裏添加片段。您的BottomNavigationView將保持不變。只需在單擊NavigationView選項卡上替換此FrameLayout中的片段即可。