簡體   English   中英

每個底部導航視圖菜單項的單獨導航圖 - Android

[英]Individual Navigation graph for each Bottom navigation view menu item - Android

我的應用程序在主活動中包含一個底部導航視圖,其中包含 3 個菜單項,每個菜單項都會在導航容器視圖中擴展各自的導航圖。 每個圖都有 2 個或更多通過動作連接的片段。

這里的問題是在屏幕方向更改期間應用程序崩潰了。 此外,底部導航不保留導航圖的 state 並且沒有為底部導航維護回棧。

下面的代碼示例。

val bottomNavigation = binding.bottom_navigation_view
navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
navController = navHostFragment.navController

bottomNavigation.setOnNavigationItemSelectedListener{ item ->
            when(item.itemId){
                R.id.navigation_home ->{
                    val navGraph = navController.navInflater.inflate(R.navigation.nav_graph)
                    navController.graph = navGraph
                    true
                }
                R.id.navigation_search ->{
                    val searchGraph=navController.navInflater.inflate(R.navigation.search_nav_graph)
                    navController.graph = searchGraph
                    true
                }
                R.id.navigation_about ->{
                    val infoGraph = navController.navInflater.inflate(R.navigation.info_nav_graph)
                    navController.graph = infoGraph
                    true
                }
            }
            false
        }

創建導航擴展 class

使用 FragmentContainerView 加載 Fragment

 <androidx.fragment.app.FragmentContainerView
            android:id="@+id/fragmentContainer"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:defaultNavHost="true" />

在 Activity 中設置 NavigationGraph

private fun setupBottomNavigationBar() {
        val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottom_nav)

        val navGraphIds = listOf(R.navigation.nav_graph, R.navigation.search_nav_graph, R.navigation.info_nav_graph)

        // Setup the bottom navigation view with a list of navigation graphs
        val controller = bottomNavigation.setupWithNavController(
            navGraphIds = navGraphIds,
            fragmentManager = supportFragmentManager,
            containerId = R.id.nav_host_container,
            intent = intent
        )

        // Whenever the selected controller changes, setup the action bar.
        controller.observe(this, Observer { navController ->
            setupActionBarWithNavController(navController)
        })
        currentNavController = controller
    }

注意:底部導航項 id 和導航圖 id 應該相同

有關更多詳細信息,您可以參考此示例項目

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM