Android Navigation Component: Start at a different destination than home, programmatically?

前端 未结 2 1384
别跟我提以往
别跟我提以往 2021-02-05 21:24

I\'m trying to implement a multiple navigation controller with multiple back stack BottomNavigationView, as per the github examples. However, the examp

2条回答
  •  半阙折子戏
    2021-02-05 21:44

    I wrote two extensions to do the job. First is to be used to change destination in the current node. The second is to be used to traverse multiple times into nested graphs

    _main_graph
     |
     |_nested_graph_1
       |
       |_nested_graph_2  
         |
         |_nested_graph_3
           |
           |_nested_graph_4
             |
             |_change this destination!!!!  
    
    fun NavController.changeNodeDestination(nodeId: Int, destinationId: Int): NavController {
        val graph = graph.findNode(nodeId) as NavGraph
        graph.startDestination = destinationId
        return this
    }
    
    fun NavController.changeNodeDestination(vararg nodeIds: Int, destinationId: Int): NavController {
        var currentNode = graph
    
        nodeIds.forEachIndexed { index, i ->
            currentNode = currentNode.findNode(nodeIds[index]) as NavGraph
        }
        currentNode.startDestination = destinationId
        return this
    }
    

    Usage:

            findNavController().changeNodeDestination(
                R.id.navigation_login,
                R.id.nav_change_password,                  // GO two levels inside nested graphs
                destinationId = startDestination
            ).navigate(navID, bundle)
    

提交回复
热议问题