Add Chrome Custom Tabs to the Android Navigation Component

Oliver Spryn
Jun 20 · 8 min read

With the introduction of Android Jetpack, developers now have a marvelous new set of libraries which offer an unprecedented level of simplicity and reusability. Before Jetpack’s debut, fragment and activity-based navigation often proved to be complicated, fragile, and nearly unique to each app on the market. Google has heard our pleas for help and given us the Navigation Component.

Current State of the Navigation Component

Since the preliminary release of the navigation component in May 2018, much of its functionality has improved, changed, and expanded. As of June 2019, the current state of this library offers native support for these destination types:

  • Fragments
  • Activities
  • DialogFragments

Support for Chrome Custom Tabs (CCT) is a notable omission from this list. Fortunately, since CCT is similar enough in behavior to activities, it is not a significant lift to add in support for this destination type.

Getting Our Thinking Straight

CCT can almost feel like magic. It is an activity which manages all of the back and forward functionality a user would expect in a normal browser without an engineer having to hijack the system’s back button or listen for an event when closing the browser with the X icon. Once the user finishes, he or she is dropped back onto the previous fragment or activity, just as expected.

In general, however, the navigation component was designed to handle switching out multiple fragments on a single activity. Therefore, when adding in CCT as a destination type, an engineer must keep in mind that the graph has no control over the browser and should not consider adding it to the component’s built-in back stack. Why? As will be the answer for most things in this article, it is because the browser handles this functionality entirely on its own, like a black box. This fact dramatically reduces the effort on our part to add in this capability.

By Charles 🇵🇭 on Unsplash

What is Required?

To declare a custom destination type for the Jetpack Navigation Component, an engineer needs to create three files:

  1. — Holds the XML definition of the destination type for Android Studio code completion and to support custom attributes.
  2. 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.
  3. 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 Schema

Technically speaking, all “destination types” are a subtype of the class. Thus, let’s create a new class called , let it inherit from , and stub all of the abstract methods.

We will, of course, have to supply a type to the generic argument for the . In practice, engineers typically create a nested class inside of first class, call it , subclass it from , and supply the stubbed navigator as a constructor parameter.

Now, the generic argument for the can receive the nested class. Altogether, the basic implementation looks like this:

A stubbed implementation of our new destination type

Depending on your needs, you may not need a 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:

  • — 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 .
  • — Provides the component with some insight regarding what kind of destination you are implementing. Since CCT is an activity, I supplied as the destination type.

Declare Customization Properties

In 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 file under the 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 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 attributes

Notice how, by convention, the name of the 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 Properties

Now that our schema is fully defined, we can begin to use these parameters in our code.

Android uses the to fetch and map these properties to code. Let’s expand our class to add the necessary support.

First, let’s add two properties, one for each parameter:

The destination has support for two customization parameters now

Then, override the method to fetch these properties from the XML and set them:

Maps the attributes from the XML file to properties in code

Notice the convention for fetching each property from the XML file. The convention is . 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 method, make sure you’ve included AndroidX Core-ktx in your Gradle configuration: .

Populate the Navigator

Now 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 and methods:

Two of the three required methods are populated

The first method, , is fairly self-explanatory since it simply returns an instance of the custom class. The method, in most cases, returns whenever the method handles the back stack operation itself, and 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, always returns .

Now, let’s tackle the method:

Grabs the URI from the argument bundle and navigates with CCT

The 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 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 . Since we return , 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 navigator

Create a Navigation Host

The built-in navigation host only supports the kind of destinations which ship with the navigation component, namely:

  • Fragments
  • Activities
  • DialogFragments

However, 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 .

This turns out to be quite easy. As described in Google’s documentation, you probably are already using the , which supports all of the built-in destinations. That is an ideal candidate as our base class. Let’s subclass it, and override the method, where we add support for our new destination:

A custom navigation host with support for our new destination type

If 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 , making this process extremely simple. Notice how the is given to the navigator by the host.

That class is the final piece of the puzzle. Let’s start using our new destination!


Putting it All Together

In 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 host

The only aspect of the above code which changes from the documentation is the 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 destinations

We 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 Chrome

Then, we can pass the information along via a safe arg, just as described in the documentation. Assuming you do your routing from the , your implementation will look similar to this:

Passes a URL as as safe arg to CCT

Now, since the safe arg is passed as a bundle to the , the bundle is unwrapped and the 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 Production

There 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 destinations

The 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 property.

Here an example of CCT working within the app:

Credits

These sources proved themselves to be incredibly helpful as I wrote my first implementation of this new destination type:

The Startup

Medium's largest active publication, followed by +524K people. Follow to join our community.

Oliver Spryn

Written by

I’m connecting people with technology, seamlessly. Since 2008, I’ve been a software architect and a leading engineer, delivering smart and intuitive software.

The Startup

Medium's largest active publication, followed by +524K people. Follow to join our community.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade