0

In my app, I want the process of creating a new record to be divided into several steps in which users are queried about different information. So I created an activity with NavHostFragment and want to use a navigation graph to switch between fragments using a next button in the toolbar of this activity.

Clicking the next button navigates to next fragment

Is it possible to configure the button to navigate between fragments based on a navigation graph? Is this a good approach? Should I rather use a new activity for each step? I am new to android development so I am not sure what is the best way to do this.

Jan Koci
  • 315
  • 3
  • 11

1 Answers1

1

You can handle it with your navigation graph

  1. Handle toolbar click events in your fragments:

    https://stackoverflow.com/a/30077965/11982611

    While handling each fragment's next button click event implement your navigation code

    findNavController().navigate(Your action)
    
  2. Handle all navigation process in your Activity's OnItemOpotionsSelected Listener

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
    
    val navHostFragment = supportFragmentManager.primaryNavigationFragment
    val fragment = navHostFragment?.childFragmentManager?.fragments?.get(0)
    
    when(item.itemId)
    {
        android.R.id.home->super.onBackPressed()
        R.id.next-> {
             if(fragment is Fragment1)
             {
                fragment.findNavController().navigate(Fragment1toFragmen2 action)}
    
             if(fragment is Fragment2)
             {
                fragment.findNavController().navigate(Fragment2toFragmen3 action)}
        }
    
        return true
    }
    
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Eren Tüfekçi
  • 2,463
  • 3
  • 16
  • 35
  • Thank you, I tried to handle the navigation in my activity using the ```onOptionsItemSelected ``` method and it works exactly as I wanted. However, when I move from fragment2 back to fragment1 the back button in my action bar disappears and is no more visible only for fragment1. Do you have an idea why? I set it in my activity with ```setDisplayHomeAsUpEnabled(true)```. – Jan Koci Nov 10 '20 at 14:35
  • It is because the navigation components backstack problem. You need to override onBackPressed method to achieve what you want. – Eren Tüfekçi Nov 10 '20 at 14:45