Add Chrome Custom Tabs to the Android Navigation Component

on UnsplashWhat is Required?To declare a custom destination type for the Jetpack Navigation Component, an engineer needs to create three files:values/attrs.

xml — Holds the XML definition of the destination type for Android Studio code completion and to support custom attributes.

Custom Navigator Class — Defines how to navigate into (push) and out of (pop) the custom destination.

Also maps the custom attributes from the XML file to the code which implements and uses those properties.

Custom Navigator Host — Adds support for the custom destination to the navigation controller.

Of course, before writing extensions for the navigation graph, you’ll need to have it included as part of your project and use Android Studio 3.

3 or newer.

Head over the Android documentation to learn how to set up the Navigation Component with Safe Args.

Define the SchemaTechnically speaking, all “destination types” are a subtype of the Navigator<D extends NavDestination> class.

Thus, let’s create a new class called ChromeCustomTabsNavigator, let it inherit from Navigator, and stub all of the abstract methods.

We will, of course, have to supply a type to the generic argument for the Navigator.

In practice, engineers typically create a nested class inside of first class, call it Destination, subclass it from NavDestination, and supply the stubbed navigator as a constructor parameter.

Now, the generic argument for theNavigator can receive the nested class.

Altogether, the basic implementation looks like this:A stubbed implementation of our new destination typeDepending on your needs, you may not need a context as a constructor argument.

I, however, know that it will be necessary for this example, so I added it up front.

You probably noticed two decorators in the above code sample.

Here is what they do:@Navigator.

Name("chrome") — Defines the name of the tag which we will use in the navigation graph’s XML file.

Thus, in this case, I will use the destination type as <chrome .

/>.

@NavDestination.

ClassType(Activity::class) — Provides the component with some insight regarding what kind of destination you are implementing.

Since CCT is an activity, I supplied Activity::class as the destination type.

By Farzad Nazifi on UnsplashDeclare Customization PropertiesIn this example, I would like to pass two styling attributes from my navigation's XML file to the destination.

Proper support for that feature starts by creating an attrs.

xml file under the values resource folder.

This chore should feel familiar if you have ever built a custom component for Android.

I would like to set the CCT toolbar and secondary toolbar colors.

Thus, my attrs.

xml file looks like this, with two properties which supply code completion for an Android reference type.

An XML file which declares support for two new attributesNotice how, by convention, the name of the declare-styleable matches the name of the custom navigator.

You could name it something different if that make more sense in your case.

However, the naming here seems to fit this example.

Fetch the Custom PropertiesNow that our schema is fully defined, we can begin to use these parameters in our code.

Android uses the ChromeCustomTabsNavigator.

Destination to fetch and map these properties to code.

Let’s expand our Destination class to add the necessary support.

First, let’s add two properties, one for each parameter:The destination has support for two customization parameters nowThen, override the onInflate() method to fetch these properties from the XML and set them:Maps the attributes from the XML file to properties in codeNotice the convention for fetching each property from the XML file.

The convention is R.

styleable.

<styleable name>_<attribute name>.

I have found that you may need to do a build before Android Studio offers autocompletion for these values.

If you are having trouble finding the withStyledAttributes method, make sure you’ve included AndroidX Core-ktx in your Gradle configuration: androidx.

core:core-ktx:$latest-version.

By Rami Al-zayat on UnsplashPopulate the NavigatorNow that the foundation for the navigator is in place, it is time to populate the navigator’s stubs.

Starting with the two easiest methods, let’s populate the createDestination() and popBackStack() methods:Two of the three required methods are populatedThe first method, createDestination(), is fairly self-explanatory since it simply returns an instance of the custom Destination class.

The popBackStack() method, in most cases, returns false whenever the method handles the back stack operation itself, and true if nothing remains on the stack for the method to pop.

Since CCT is an activity with its own fully-managed back stack, there is nothing for the navigation graph to do.

By the time CCT pops itself off the stack, drops the user back onto the prior view, and the navigation graph is reactivated, all back navigation has been handled for free.

Thus, popBackStack() always returns true.

Now, let’s tackle the navigate() method:Grabs the URI from the argument bundle and navigates with CCTThe navigate() method simply wraps CCT’s builder and launch methods, as described in their documentation.

The toolbar colors are extracted from the properties of the custom Destination class we wrote earlier and applied to the builder.

Last, the argument bundle extracts a URI, casts it, and passes it to the launch procedure.

Once again, since CCT manages its own back stack, we do not return any kind of NavDestination.

Since we return null, that prevents the navigation graph from adding the CCT destination to its own back stack, and thereby causing some weird back press behavior.

That was the hard part.

Here is the navigator in its full glory:The full-fledged navigatorCreate a Navigation HostThe built-in navigation host only supports the kind of destinations which ship with the navigation component, namely:FragmentsActivitiesDialogFragmentsHowever, we will probably have a graph which contains not only our custom destination type, but also a mix of the above destinations.

Thus, we will need to subtype the built-in navigation host, and shim in support for the ChromeCustomTabsNavigator.

This turns out to be quite easy.

As described in Google’s documentation, you probably are already using the NavHostFragment, which supports all of the built-in destinations.

That is an ideal candidate as our base class.

Let’s subclass it, and override the onCreateNavController() method, where we add support for our new destination:A custom navigation host with support for our new destination typeIf we do not explicitly add in this type of support, the navigation graph will throw an exception and say that it cannot handle your custom destination.

Fortunately, all of the hard work is already handled by the NavHostFragment, making this process extremely simple.

Notice how the context is given to the navigator by the host.

That class is the final piece of the puzzle.

Let’s start using our new destination!By Yahdi Romelo on UnsplashPutting it All TogetherIn this example, I’ll create a simple activity, which contains only the navigator host.

We will have to use our custom host in our activity layout file:Implements our custom navigation hostThe only aspect of the above code which changes from the documentation is the android:name property, to point to our custom navigator host.

The rest of the code sample is derived from the relevant Google documentation.

Next, we will need to add a CCT destination to our graph.

Again, referring to the documentation, we can build up our graph with activities, fragments, and dialog fragments.

Let’s add in a link to CCT:A navigation graph with two destinationsWe could have written our implementation so that the URL was provided as an attribute in the XML.

However, since I wanted more flexibility, my implementation uses arguments to pass along this information.

To send this necessary information to CCT, add in an action with an argument:An action which allows the passage of a URL to ChromeThen, we can pass the information along via a safe arg, just as described in the documentation.

Assuming you do your routing from the MainActivity, your implementation will look similar to this:Passes a URL as as safe arg to CCTNow, since the safe arg is passed as a bundle to the ChromeCustomTabsNavigator, the bundle is unwrapped and the uri parameter is extracted, as shown earlier in our implementation above.

Viola!.We have a fully working custom destination which opens Chrome Custom Tabs, integrates into the navigation graph, and preserve the back button functionality in Android.

Expansion and Usage in ProductionThere are plenty of ways this example can be modified and expanded to include more powerful functionality.

Before we say ????, you may be interested to see how this is used in a production app.

Here is a screenshot of how the CCT destination works in one of the modules of the MyUPMC app:A working graph with fragments, an activity, and three CCT destinationsThe orange screens are the CCT destinations.

For visual clarity, I created a simple layout which I do not use within the app, but apply to the graph with the tools:layout="@layout/graph_placeholder_chrome property.

Here an example of CCT working within the app:CreditsThese sources proved themselves to be incredibly helpful as I wrote my first implementation of this new destination type:https://developer.

android.

com/guide/navigation/navigation-getting-startedhttps://developer.

chrome.

com/multidevice/android/customtabshttps://gist.

github.

com/fbarthelery/ad0062a88875b46e0065137ff03807a0https://proandroiddev.

com/jetpack-navigation-with-custom-views-c763255c9599.. More details

Leave a Reply