首页 > 解决方案 > 如何实现带有底部导航的导航组件?

问题描述

我有一个活动和三个片段(AddFragment、QuoteFragment 和 CalendarFragment)。主要活动在底部应用栏和片段容器内有一个底部导航。我想要的是将底部导航项与片段链接,有什么简单的方法吗?

activity_main.xml

<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=".MainActivity">

    <androidx.fragment.app.FragmentContainerView
        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/nav_graph"/>

    <com.google.android.material.bottomappbar.BottomAppBar
        android:id="@+id/bottomAppBar"
        style="@style/Widget.MaterialComponents.BottomAppBar.Colored"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom">

        <com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@+id/bottomNavigation"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:menu="@menu/bottom_app_bar"
            android:background="@android:color/transparent"

            />

    </com.google.android.material.bottomappbar.BottomAppBar>


    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/ic_add_24"
        app:layout_anchor="@id/bottomAppBar"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

MainActivity.kt

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.bottomNavigation.setBackground(null)

    }
} 

标签: androidkotlin

解决方案


推荐阅读