Jetpack Navigation: Getting Started

Aug 10 2021 · Kotlin 1.4, Android 11, Android Studio 4.2.1

Part 2: Create Destinations & Navigate via Actions

06. Add Destinations & Navigate via Action

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 05. Add Start Destination & NavHost Interface Next episode: 07. Pass Data Between Destinations

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Transcript: 06. Add Destinations & Navigate via Action

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!