Jetpack Compose Theming for Existing Apps (Part 3) Creating an Adapter

When not using Material Design Components

Yoel Gluschnaider
2 min readJan 3, 2021

In the first part of these 3 parts series about JC Theming, I detailed the two paths possible to transition your app’s theme from an XML based one to a JC theme based system. In the previous post I described how to create your own custom theme for JC and in this post I am going to describe how to create an adapter to have your current XML based theme exposed as a JC theme component. It is important to read the previous post before this one as it relies on the concepts described there such as CompositionLocals and CompositionLocalProviders as well as the actual API of the theme component.

What is the Adapter’s Purpose?

In a nutshell — to take the values we have in XML and put them inside our JC based theme. We will use the same example as in the previous post and here is the MyTheme component:

Our adapter’s signature is fairly straight forward:

The createMyTheme function will extract the values from the XML and create the MyThemeParameters class. Let’s imagine you have the following theme in XML:

And the actual theme colours like this:

The Adapter’s Implementation

To read values from XML themes one needs to use something called TypedArray. If your adapter code will live in the same library as the my_theme.xml file or depend on the library containing it, then you can skip the next step.

Duplicating the XML

We need access to the stylable attributes, but we do not have their ID as it is in a different library. Therefore, we create a duplicate stylable attributes list to be used in our adapter’s code allowing it to be completely stand alone from the existing design system (as it is the case with the MDC theme adapter that is a standalone library). We will create the following XML:

Important to note! the names of the attributes have to be identical to the ones you set in your theme attributes!

Read the XML

To read the XML we use this theme we created and thus having access to the actual colour assigned to that styled attribute:

As you see — we use the MyThemeAdapterTheme to retrieve the colours from the current context as the colour attributes have the same name as the original and therefore the same index in the TypedArray.

That’s basically it. Once we have the values, we can create the MyColors class and the MyThemeParameters class. Small thing we do is to check if we have the value in the XML theme, just to avoid throwing an exception and having a graceful fallback.

Using the Adapter

To use the adapter function, you call it when creating the theme component as default value:

Hope you liked this 3 part series on JC theming. Happy coding and as always — comments are very welcomed!

--

--