You will add LoginFragment as and SignUpFragment as new Destionations in this episode. Open navigation graph in starter project. Click New Destination icon. Select LoginFragment. A
gain Click New Destination icon and select SignUpFragment. Move both to the right of MainFragment in the graph.
Now with MainFragment selected, drag the Arrow from MainFragment to LoginFragment until it shows LoginFragment selected.
Repeat the same for SignUpFragment. So Cool and Quick, isn’t it! Now Switch to Code view and see the LoginFragment and SignUpFragment added as destinations.
Also, notice, actions added inside MainFragment.
These are pretty simple and readable, indicating where you navigate to for a particular action. Modify the first action and rename it to actionLogin for simplicity.
Similary, Modify the second action and rename it to actionSignUp. Now you’ll modify the MainFragment to tie destinations to UI. Open MainFragment.kt
Here you need to get hold of NavController in order to Navigate. In Kotlin, it’s recommended that you use one of the extension functions.
From within an Activity, use findNavController with viewId where viewId is the id of NavHostFragment .
From within a Fragment, simply call findNavController , however the fragment has to be either NavHostFragment or has NavHostFragment as parent.
From within an onClickListener of view in Fragment, call view.findNavController().
In Java, use these static functions.
Return to the MainFragment in the Project and set the click listener of Login Button now by adding following code:
v ->
v.findNavController().navigate(R.id.actionLogin)
If Android Studio prompts you for import, import androidx.navigation.findNavController
HERE you navigate by specifying the ID of the Action set in the Navigation Graph. You can also specify the Id of the Destination Fragment to navigate. Now do the same for SignUp button.
v -> v.findNavController().navigate(R.id.actionSighUp)
Now build and run the app.
Click on Login.
It takes you to Login screen. Click on Sign Up.
It takes you to Sign up screen. Awesome! How easy it is to Navigate via actions!