Search code examples
androidkotlinandroid-architecture-navigation

Signup flow with advanced navigation example


I am currently using bottom navigation like in navigation advanced example, I am trying direct user to signup flow if user is not authenticated. I use following code in side defaultly selected fragment to direct user to sign up flow (login_nav_graph) if they are not authenticated.

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)


        if(!authenticated){
            view.findNavController().navigate(R.id.action_frag1Fragment_to_login_nav_graph)
        }
    }

But there are few problems

  • Shows back button when user in signup flow
  • Bottom navigation is shown in signup flow

These problems make sense, Reasons:

  • since signup flow (login_nav_graph) is nested inside bottom navs first items(defaultly selected) navigation graph.
  • Bottom nav is on activity_main layout.

So how could I integrate signup flow into navigation advanced example and overcome above mentioned issues with a better approach?

Note:

code is very similar to navigation advanced example, I introduced separate nav graph for signup flow called login_nav_graph and above mentioned code in defautly selected fragment


Solution

  • Fixed the issue by doing following.

    1. Add login_nav_graph to the nav graph which contains defaultly selected fragment as a nested nav graph.
    2. Create an action/path from defaultly selected fragment (frag1Fragment) to the login_nav_graph and set the Pop To behavior of the action to the frag1Fragment's nav graph.

    3. Create following two methods inside the MainActivity in order to toggle the visibility of the action bar and bottom nav.

      fun toggleBottomNavVisibility(){
      
          if(bottom_nav.visibility == View.VISIBLE){
              bottom_nav.visibility = View.GONE
          }else{
              bottom_nav.visibility = View.VISIBLE
          }
      }
      

    ...

    fun toggleActionBarVisibility(){
    
            if(supportActionBar!!.isShowing){
                supportActionBar?.hide()
            }
            else{
                supportActionBar?.show()
            }
    }
    
    1. Update the onViewCreated method of the frag1Fragment as follows

    ...

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
    
        if(!authenticated){
    
            // hide bottom navigation and action bar
            val activity = activity as MainActivity
            activity.toggleBottomNavVisibility()
            activity.toggleActionBarVisibility()
    
           findNavController().navigate(R.id.action_frag1Fragment_to_login_nav_graph)
        }
    }