App development

Navigation Element for Android Half 2: Graphs and Deep Hyperlinks [FREE]

Navigation between Fragments utilizing the FragmentManager is a nightmare most Android builders attempt to keep away from. Normally, the Fragment lifecycle doesn’t play properly with the Exercise lifecycle.

Managing the Fragment again stack is one other headache, particularly whenever you add deep hyperlinks to the combination. At Google I/O ’18, Jetpack Navigation part got here to the rescue. The Navigation part takes the duty of the FragmentManager so builders can concentrate on constructing superior options of their apps.

A few of the options within the Navigation part Model have been already coated in The Navigation Structure Element Tutorial: Getting Began. On this tutorial, you’ll find out about these cool Jetpack Navigation part options:

DialogFragment in navigation graph.
ViewModel per navigation graph.
Protected Args.
Nested graph.
Specific and implicit deep hyperlinks.

To embark on a romantic navigation journey, you’ll construct a Love Letter app. As you would possibly guess from the title, this app permits allows you to ship and obtain love letters.

Getting Began

A few of the Navigation part options on this tutorial require Android Studio three.four or increased. Be certain that to put in the most recent steady launch.

First, obtain the supplies for this tutorial utilizing the Obtain supplies button on the high or backside of this tutorial. Open the mission with Android Studio. You’ll be prompted with a dialog to decide on Gradle wrapper:

Import Project From Gradle

Click on OK. You’ll discover the mission construction appears to be like like this:

Project Structure

Check out the fragments package deal:

InboxFragment: Checklist of letters you acquired.

SentFragment: Checklist of letters you despatched.

CreateLetterFragment: The place you compose and ship your letter.

PresentationFragment: The place you view the content material of the letter.

EditProfileFragment: Dialog for inputting your title and e mail handle.

There are two extra Fragments contained in the settlement package deal:

PrivacyPolicyFragment: Lengthy, boring textual content for the privateness coverage no one cares about.

TermsOfServiceFragment: Extra lengthy, boring textual content for the phrases of service no one bothers to learn.

Listed here are different necessary lessons:

LetterAdapter: RecyclerView adapter for checklist of letters.

LetterPagerAdapter: ViewPager adapter for letter presentation.

Occasion: LiveData worth wrapper that makes observer learn its worth solely as soon as.

KotlinExtension: Incorporates just a few short-handed capabilities to make the code cleaner.

LetterRepository: Repository class for Letter CRUD operations.

LetterViewModel: The one ViewModel on this app for MainActivity and different Fragments.

MainActivity: The only Exercise the place navigation is setup.

To ensure all the things is appropriate and dealing, run the app. You need to see an empty display like this:

Empty Screen

The floating motion button with the envelope icon is just like the Compose button on Gmail app. It’ll convey you to the CreateLetterFragment.

Slide from the left edge to view the navigation drawer. All of the drawer menu gadgets are setup for you:

Navigation Drawer

Including Dependencies

Open construct.gradle beneath app module. Add the next code into dependencies braces under // TUTORIAL DEPENDENCIES:

def nav_version = “”

implementation “androidx.navigation:navigation-fragment-ktx:$nav_version”
implementation “androidx.navigation:navigation-ui-ktx:$nav_version”

Run Gradle sync by means of Android Studio. If there aren’t any errors, you’re good to go.

Inflating Format to Fragment in AndroidX

Since you added androidx.navigation:navigation-fragment-ktx, you’re now in a position to set the format for the Fragment immediately in its constructor. Open the next 5 information one by one, and add the format id to every constructor:

class InboxFragment : Fragment(R.format.fragment_inbox)

class SentFragment : Fragment(R.format.fragment_sent)

class PresentationFragment : Fragment(R.format.fragment_presentation)

class PrivacyPolicyFragment : Fragment(R.format.fragment_privacy_policy)

class TermsOfServiceFragment : Fragment(R.format.fragment_terms_of_service)

The advantage of this method and setting the format within the Fragment constructor is that you simply don’t must override onCreateView() and write boilerplate code to inflate the format and return it.

Constructing Graphs With the Navigation Element

Proper click on the res folder in Undertaking Explorer, then create a brand new Listing named navigation. Proper click on the navigation folder and create a brand new Navigation useful resource file named nav_graph. You’ll be delivered to the Navigation Editor:

Navigation Editor

Add the next 5 fragments and the settlement graph to the editor. Join them as within the screenshot under:

InboxFragment, set as dwelling fragment.
EditProfileFragment, proven as a dialog.

Navigation Graph

You solely want to attach the motion from InboxFragment and SentFragment to PresentationFragment. You’ll discover out why within the Protected Args part under.

Swap the view mode from Design to Textual content. Fill in navigation id, motion id and fragment label. Then, fill in format because the code under, or just copy and paste:

Notice: The

tag is used as a substitute of for EditProfileFragment, in any other case the fragment would take up the total area on the display.

If the fragments in Navigation Editor don’t render any format, guarantee that the instruments:format attributes are added. You possibly can additionally merely rebuild the mission.

You’ve completed constructing the navigation graphs. Now you’re prepared to make use of nav_graph in content_main.xml.

Including NavHostFragment With Navigation Element Graph

Open content_main.xml and add the next code contained in the ConstraintLayout:

What it is best to discover right here:

android:title=”androidx.navigation.fragment.NavHostFragment”: You’re utilizing NavHostFragment from Androidx to host your navigation graph.

app:navGraph=”@navigation/nav_graph”: You’re supplying your navigation graph to the NavHostFragment.

Now it’s time to let your MainActivity know concerning the NavHostFragment and navigation graph.

Establishing Navigation Element in MainActivity

Open MainActivity.kt and look at the code. You’ll see some code for navigation drawer and information binding is already there. Information binding binds the profile title and e mail to the navigation drawer header.

There are a bunch of TODOs that can assist you know the place to insert the code snippets.

Proper under the MainActivity class declaration, add the next two personal fields:

personal val navController by lazy //1
personal val appBarConfiguration by lazy //2

Right here’s what you probably did:

You’ll use navController to navigate from one fragment to a different. Import findNavController from androidx.navigation.findNavController.

appBarConfiguration defines which fragments are the highest stage fragments so the drawerLayout and hamburger icon can work correctly. You’ll perceive why whenever you run the app.

Connecting Toolbar, Drawer and Navigation Controller

Right here’s crucial code on this tutorial. When you’re nonetheless in MainActivity, add the next code inside setupNavigation:

NavigationUI.setupActionBarWithNavController(this, navController, drawerLayout) //1

NavigationUI.setupWithNavController(toolbar, navController, appBarConfiguration) //2

navController.addOnDestinationChangedListener _, vacation spot, _ -> //three
if (vacation in arrayOf(,,
) else

if (vacation == else
toolbar.visibility = View.VISIBLE

Right here’s what this code does:

Join your navController with drawerLayout.
Join your toolbar, navController and appBarConfiguration collectively. This makes your navController conscious of top-level fragments outlined in appBarConfiguration.
Customise your floating motion button and toolbar primarily based on the vacation spot fragment. Right here you wish to conceal your floating motion button whenever you’re on CreateLetterFragment, PresentationFragment and EditProfileFragment. On PresentationFragment, conceal the toolbar as a way to learn your love letters with out distraction.

Now, run the app. You need to now see the hamburger icon. It wasn’t there whenever you first ran the app. That’s due to the second line of the code above.

The title at instrument bar is exhibits the label of InboxFragment, which is the present Fragment.

Inbox Screen

Click on the hamburger icon or slide from the left aspect of the display. You’ll see the drawer is open. However should you click on on any menu merchandise, you continue to can’t navigate to any fragment but.

Navigating From Drawer Menu Objects

Inside onNavigationItemSelected, you’ll discover the when block for every menu merchandise. Exchange the
content material contained in the when block with the next code: ->
navController.popBackStack(, false) //1 ->
navController.navigate( //2 ->
navController.navigate(Uri.parse(“loveletter://settlement/privacy-policy”)) //three ->

Right here’s what you added:

Since InboxFragment is the house fragment, you employ popBackStack to take away different fragments from the navigation stack. The second parameter signifies whether or not InboxFragment must also come out of the stack.

Straight ahead. This makes use of the navController to navigate to SentFragment.
It is a deep hyperlink URI to PrivacyPolicyFragment. You’ll find out about this in just a few sections.
That is additionally a deep hyperlink URI, however for TermsOfServiceFragment.

Now, run the app. You need to have the ability to navigate between InboxFragment and SentFragment.

That’s it. You now not must get SupportFragmentManger or commit a fraction transaction with the intention to swap fragments.

Open Sent

Notice: At present, should you click on on Privateness Coverage or Phrases of Service the app will crash. It is because no app is dealing with the URI you outlined within the code snippet above.

Navigating From Floating Motion Button

In MainActivity.kt, find setupViews() and add the next code inside


Just like the way you navigate to SentFragment, you employ navController to navigate to
CreateLetterFragment by its id.

Run the app and click on the floating motion button. You’ll see the app navigates to CreateLetterFragment.

The loading progress bar retains on spinning. It’s an annoyance, however you’ll be able to ignore it for now.

Create Letter Screen

Subsequent, you’ll wire the edit profile dialog.

Exhibiting DialogFragment

In case you’ve tried exhibiting DialogFragment in Navigation part or adopted The Navigation Structure Element Tutorial: Getting Began tutorial, you may have prolonged Navigator class and applied your individual present dialog logic.

This isn’t required with Navigation part Check out the code in nav_graph.xml. You’ll see the tag dialog is robotically used for fragments extending DialogFragment.

To indicate the dialog fragment, you need to add the next line inside the clicking listener of headerBinding.ivEdit in MainActivity:


As soon as once more, we’re utilizing the navController to navigate to a different fragment. On this case the Edit Profile Fragment. Run the app and click on the Edit Profile button.

Yay! The dialog pops up with only some strains of code.

Open Edit Profile Dialog

Subsequent, you’ll set the ViewModel so it can save you and present your profile info.

ViewModel Throughout Navigation Graph

ViewModel is a design sample launched to separate the enterprise logic and life cycle occasions out of your Exercise and Fragment. Since your fragments stay beneath an Exercise, it’s frequent to make use of one shared ViewModel for the Exercise and its related fragments.

Within the Navigation part, you’ll be able to initialize a ViewModel with a navigation graph scope. This implies all of the fragments in the identical navigation graph and their guardian Exercise share the identical ViewModel.

Getting ViewModel in Exercise From Navigation Graph

When you’re nonetheless in MainActivity.kt, add the next code to setupViewModel():

val viewModelProvider = ViewModelProvider(
) //1
lettersViewModel = viewModelProvider.get( //2
headerBinding.viewModel = lettersViewModel //three
lettersViewModel?.loadProfile() //four
catch (e: IllegalArgumentException)

Right here’s a breakdown of the above code:

As an alternative of the same old means of getting ViewModelProviders from Exercise or Fragment like ViewModelProviders.of(this), right here you get ViewModelProvider from navigation graph id, which is This ensures you’re utilizing the identical ViewModel throughout complete graph.
Get your LettersViewModel from viewModelProvider, which you created within the line above.
That is the info binding logic for the header within the navigation drawer. In case you’re curious, verify nav_header_main.xml. The header binding requires the viewModel occasion of LettersViewModel class.
Load profile info from SharedPreferences.
An exception occurs when the app is launched by way of a deep hyperlink. Navigation part can’t deal with the initialization of a ViewModel scoped to Navigation graph. The non permanent answer is to catch the exception.

The main points of ViewModel implementation aren’t mentioned right here because it’s not a part of the Navigation part. Spend some instances studying the code in LettersViewModel to grasp how the ViewModel, Information Binding and Room function behind the scenes.

Now your drawer header is able to present profile info from shared preferences. However nothing is saved to shared preferences but! You’ll want to do one thing within the EditProfileFragment.

Getting ViewModel in Fragment From Navigation Graph

Open EditProfileFragment.kt and exchange the declaration of lettersViewModel with the next line:

personal val lettersViewModel: LettersViewModel by navGraphViewModels(

That is a lot cleaner than how you bought your ViewModel in MainActivity earlier. Because of navGraphViewModels(…), the prolonged inline operate for Fragment, you will get the occasion of LettersViewModel with one line of code.

Launch the app and edit your profile info within the dialog. Click on the Save button and verify your profile within the drawer once more.

Voila! Your title and e mail are there! In case you open the EditProfileFragment dialog once more, your title and e mail are stuffed by default.

That’s the magic of information binding. :]

Fill In Edit Profile Dialog

Creating Your First Love Letter

Open CreateLetterFragment.kt and exchange the declaration of lettersViewModel with the next code:

personal val lettersViewModel: LettersViewModel by navGraphViewModels(

As soon as once more, it’s the identical line to get the occasion of the identical ViewModel.

Within the Create Letter Fragment, you may need observed there are two choice menu gadgets:

PUSH: Create an area push notification. This mimics the notification the app sends when your recipient receives your letter. On this tutorial, you’ll solely ship love letters to your self.

SEND: Create an online URI for a deep hyperlink. The URI is meant to be embedded within the love letter e mail. If the recipient additionally has the Love Letter app put in on his or her telephone, when she or he clicks the URI within the e mail app, the telephone ought to launch the Love Letter app to deal with the deep hyperlink.

Once you click on SEND or PUSH, handleSend will get known as. Check out handleSend.

personal enjoyable handleSend(toSend: () -> Unit)
if (lettersViewModel != null && lettersViewModel.hasFullProfile()) else

handleSend is checking if there may be any profile info. It’s ensuring the title and e mail aren’t empty.

If there may be profile info, invoke toSend lambda and navigate to SentFragment. In any other case, present EditProfileFragment dialog.

Based mostly on this logic, exchange the implementation of handleSend with the next code:

if (lettersViewModel.hasFullProfile()) else
findNavController().navigate( //three


Right here’s a breakdown of the code above:

In a fraction, name findNavController() to get the navigation controller. After you’ve carried out your despatched motion, exit CreateLetterFragment and go to SentFragment to see what you’ve despatched. You’ll be able to’t popBackStack on to SentFragment as a result of it won’t be within the navigation stack.

The work round right here is to return to InboxFragment, which is the house fragment, first.

Right here you go to SentFragment from InboxFragment.
If the app doesn’t have profile info, go to EditProfileFragment.

Notice: There are just a few variants of findNavController(). Be certain that to import the one beneath androidx.navigation.fragment.

Earlier than you’ll be able to check the PUSH operate, it is advisable to find out about how one can generate a push notification with deep hyperlink.

Constructing Notification With Specific Deep Hyperlink

There are two forms of deep hyperlinks:

Specific: An express deep hyperlink is a single occasion of a deep hyperlink that makes use of a PendingIntent to take customers to a particular location inside your app.

Implicit: An implicit deep hyperlink is a URI that refers to a particular vacation spot in an app.

Open NotificationHelper.kt. Look at the code and also you’ll discover three strategies:

sendLocalNotification: Will get notificationManager from context and sends the notification.

sendLocalNotification: Builds a notification from the letter object.

buildPendingIntentFromNavigation: Builds a pending intent to navigate to particular fragment when notification banner is clicked.

There’s no implementation inside buildPendingIntentFromNavigation but. Exchange the code inside buildPendingIntentFromNavigation with the code under:

val bundle = Bundle()
bundle.putString(EXTRA_LETTER, gson.toJson(letter)) //1
return NavDeepLinkBuilder(context) //2
.setGraph(R.navigation.nav_graph) //three
.setDestination( //four
.setArguments(bundle) //four
.createPendingIntent() //5

Right here you:

Create the bundle which incorporates the serialized letter string.
Use NavDeepLinkBuilder to construct a pending intent.
Cross in your navigation graph useful resource id.
Cross in your fragment ID in navigation graph.
Generate the pending intent. Carried out!

Run the app and ship your old flame letter. Go to the create letter display from the floating motion button. Write a message to the one you love and click on the PUSH button.

You need to see a push notification on the highest of your display. Clicking the notification gained’t work since you haven’t configured the PresentationFragment.

Push Notification

Create one other letter and click on the SEND button. Observe the Logcat in Android Studio. You’ll see a hyperlink like this:

Logcat of Sent Message

You’ll use this hyperlink for the implicit deep hyperlink implementation in a later part.

What should you haven’t stuffed in your profile info? If you have already got profile info, click on the edit profile button from the drawer header, clear the title and e mail subject and click on SAVE.

Now return to create letter display, click on both the PUSH or SEND button. You’ll see the edit profile dialog! That is actually cool as a result of you’ll be able to reuse the dialog with one line of navigation code.

Passing Letter With Protected Args

Protected Args is a Gradle plugin that generates objects and builder lessons for type-safe entry to arguments specified for locations and actions. In different phrases, it forces you to go right and enough arguments into the fragment whenever you navigate to it.

To make use of Protected Args, open construct.gradle beneath app. Add the next line of code the highest of the file:

apply plugin: “androidx.navigation.safeargs.kotlin”

Run Gradle sync in Android Studio once more.

Now, you’ll make PresentationFragment require a serialized Letter string as an argument. PresentationFragment converts the serialized Letter string into an object and assigns it to the ViewPager.

Open nav_graph.xml, on Design view, then click on the presentationFragment within the graph on the left. On the Attributes panel, you’ll discover the Arguments part. Click on the + on the correct hand aspect.

Attributes Panel

Title the argument letter and set its sort as String. Click on Add. That’s it.

Add Letter Argument

Getting Letter From Protected Args

Open PresentationFragment.kt. Assign lettersViewModel to the navigation graph ViewModel:

personal val lettersViewModel: LettersViewModel by navGraphViewModels(

Then, add the next line of code proper under the road above to get the argument’s object:

personal val args: PresentationFragmentArgs by navArgs()

Notice: PresentationFragmentArgs is a generated class. If the compiler offers you an error saying that it may well’t discover the category, be certain to construct your mission in Android Studio first.

Inside onViewCreated, beneath tremendous.onViewCreated(view, savedInstanceState), add the next code:

val letter = Gson().fromJson(
args.letter.urlDecode(), //1
lettersViewModel.saveLetterToInbox(letter) //2

viewPager.adapter = context?.let

Right here’s a breakdown of this code:

The args object incorporates the letter argument. It’s sort is String. You’ll be able to go to its declaration to see the code of the generated class. urlDecode() is a String extension that decodes the URL-encoded string as a result of the serialized Letter is used as part of URL.

Save the opened letter to inbox. This mimics the habits of receiving the letters within the inbox so you’ll be able to reopen them.
Cross the Letter object to the ViewPager. The ViewPager presents the letter in three sliding pages.

You’ve setup the PresentationFragment. Now you’ll be able to PUSH a brand new letter and open it from a push notification!

Open From Push Notification

Give your self a pat on the again! :]

Seeing What You’ve Despatched

Open SentFragment.kt. To see the letters you’ve despatched, it is advisable to assign the identical nav-graph-scoped ViewModel to lettersViewModel. Assign the worth to lettersViewModel as follows:

personal val lettersViewModel: LettersViewModel by navGraphViewModels(

No shock right here. It’s the identical previous code.

Subsequent, deal with the clicking on a RecyclerView merchandise. Add the next code to adapter.setItemClickListener:


Thus far, you’ve used navigation by fragment id. Within the line of code above, you employ the generated SentFragmentDirections class.

Navigation part generates a category for every fragment which has an motion to a different fragment. The title of the generated class is the title of the originating vacation spot, appended with the phrase Instructions.

presentLetter is the id you gave the motion from SentFragment to PresentationFragment. Right here, you employ it to go the protected args.

End the following step earlier than operating your app. It’ll be a fast one.

Seeing What You’ve Acquired

Repeat the identical steps from SentFragment in InboxFragment. In InboxFragment.kt, Assign the worth to lettersViewModel as follows:

personal val lettersViewModel: LettersViewModel by navGraphViewModels(

Add the next code to adapter.setItemClickListener:


Now you’ll be able to check the entire circulate of sending and receiving a love letter. You need to see letters within the SentFragment and InboxFragment. Clicking any letter within the checklist ought to open the PresentationFragment.

Inbox To Sent Screens

Nested Graph

In case you’re constructing a large-scale app, it is best to create completely different graphs for modularization and reusability. Just like format information, you’ll be able to nest a brand new graph within the present graph.

You’ll create one other graph for Privateness Coverage and Phrases of Service. Create one other navigation graph in the identical location as nav_graph.xml. Title it agreement_graph.xml.

Add PrivacyPolicyFragment and TermsOfServiceFragment to Navigation Editor.
Set PrivacyPolicyFragment as the house fragment.
Join PrivacyPolicyFragment to TermsOfServiceFragment.
Swap to Textual content view and alter their label to correct title from String useful resource.
Set the id of the navigation graph to android:id=”@+id/agreement_graph”.

Agreements Graph

Subsequent, swap to nav_graph.xml. Add the nested agreement_graph the identical means you added the opposite fragments in Design view. That’s by clicking the new vacation spot button, you don’t have to attach any fragment to the nested graph.

Now, how do you navigate to the nested graph?

Nested Agreements Graph

Creating Implicit Deep Hyperlink With URI

The reply is straightforward: Use a deep hyperlink. Extra exactly, use an implicit deep hyperlink. Implicit deep hyperlinks permit you to navigate to any fragment by URI.

Return to agreement_graph.xml. In Design view, with PrivacyPolicyFragment chosen, discover the Deep Hyperlinks part on the Attributes panel.

Deep Link Attribute

Click on the + signal, and add the next deep hyperlink within the URI textfield:


Add Privacy Policy Deep Link

Repeat the steps above so as to add one other deep hyperlink for TermsOfServiceFragment:


Add Terms of Service Deep Link

Do you bear in mind the Privateness Coverage and Phrases of Service drawer menu gadgets at first of the tutorial? Now that all the things is related, you’ll be able to check them out.

Open Agreement Screens

Dealing with Net URL Deep Hyperlink

Assume you personal When somebody sends a love letter, you wish to embed a hyperlink within the e mail.

If the recipient clicks the hyperlink on his telephone app consumer, and his telephone has Love Letter app put in, the telephone ought to immediate the recipient to launch the app to see the letter. In any other case, the recipient ought to have the ability to open the letter on any internet browser.

Open AndroidManifest.xml. Add the next line inside and above :

It is a essential step that’s simple to overlook. When you have one other deep hyperlink to a different navigation graph, bear in mind so as to add the graph right here.

Subsequent, go to nav_graph.xml. Add the next deep hyperlink to PresentationFragment:

Don’t embrace http:// or https:// for internet URL. letter is the encoded-URL which ought to handed to PresentationFragment.

Does the URL appears to be like acquainted? You noticed it within the Logcat whenever you clicked the SEND button on CreateLetterFragment. Right here, you configure it to deal with that hyperlink.

With all of the puzzle items full, you’ll be able to check the deep hyperlink like this:

Go to Run ▶ Edit Configurations.

Add new a Android App configuration.

Title it letter-deeplink.

Choose Module: app.

Choose Launch: URL.

Paste within the URL you bought from Logcat after you clicked the SEND button.

Click on OK to complete.

Run Configurations

Change the run configuration from app to letter-deeplink and run it.

Launch App With Deep Link

The place to Go From Right here?

Congrats! You need to now have the ability to navigate to any fragment in any means by controlling the actions and locations with the Navigation part.

You’ll be able to obtain the completed mission with the Obtain supplies button on the high or backside of the tutorial.

Jetpack Navigation part additionally works with Backside Navigation. Attempt including Backside Navigation and connecting it to the navigation controller with NavigationUI.setupWithNavController(…).

Yow will discover extra examples of Navigation on the official Android Developer web site. You too can discover a checklist of tips for Navigation on Android Builders weblog.

When you have any questions or feedback on what you’ve discovered, be a part of the discussion board dialogue under!

wordpress autoblog
amazon autoblog
affiliate autoblog
wordpress web site
web site growth

Related posts

Giveaway: Oculus Rift VR Headset [FREE]


Oculus Rift Giveaway Winner and Final Day for AR/VR Sale! [FREE]


UIDocument From Scratch [FREE]


Leave a Comment