Getting Started With Jetpack Compose

Jetpack Compose, sounds fancy right? Well, it is as fancy as it sounds, being a modern UI toolkit that is designed to simplify UI development in Android. It consists of a reactive programming model with conciseness and ease of Kotlin programming language. It is fully declarative so that you can describe your UI by calling some series of functions that will transform your data into a UI hierarchy. When the data changes or is updated then the framework automatically recalls these functions and updates the view for you. In this article, we will see some of the basic topics which are helpful before starting with Jetpack Compose.

· What is Jetpack Compose?

· What are its benefits?

· What challenges we can solve by using Jetpack Compose?

· How do we get started with Jetpack Compose?

· Composable Functions

· Layouts

· Material Design

· Lists and Animations

· Conclusion

What is Jetpack Compose?

Check out the tutorial video for a complete walkthrough

Less code plus more power to develop. That defines Jetpack Compose perfectly as it is a modern UI toolkit recently launched by Google which is used for building native Android UI. It simplifies and accelerates the UI development with less code, Kotlin APIs, and powerful tools.

What are the Benefits of Using Jetpack Compose?

· Declarative: It is fully declarative so that you can describe your UI components by calling some predefined functions.

· Compatible: It is easily compatible with the existing views present in Android.

· Increase development speed: Previously developers worked on the XML file and Kotlin file. But with the help of jetpack compose this becomes easy and developers only have to work on the Kotlin files that’s why it will help developers in increasing development speed.

· Concise and Idiomatic Kotlin: Jetpack Compose built the UI with the benefit that Kotlin brings.

· Lesser Files: As the codebase of any application is present in a single file. It becomes easy to manage and handle the codebase of the application.

· Written in Kotlin: The application written using jetpack compose uses only Kotlin programming language.

What Challenges Can We Solve using Jetpack Compose?

· When writing our code we create multiple methods for different purposes. After that we couple this method in our main function according to our requirement. In Android when building any type of view and setting data to that particular view. First of all, we initialize that view with a variable and then add data to that specific view. This process of grouping UI elements with the View Model is called Coupling. When our code is having so many couplings it becomes difficult to maintain this code. So coupling can give you sometimes some errors pertaining to Null References.

· While developing apps in Java we generally prefer using View Modal concept in which we find each view from our XML layout file inside our Java class and add data to that specific view according to our requirement. In most apps, we use the UI elements to display dynamically so this may sometimes give you an error of Null Reference. In this method, UI elements are declared in XML language whereas the functionality is written in java or Kotlin and we link UI elements with our Java or Kotlin class with the findViewbyId() method.

· If we prefer to use the same language for writing our UI components and for adding the functionality it will help us make it easier to maintain our code. By using this method the number of couplings inside our code will also reduce.

· Now that a firm base has been formed, lets get started with some fun practical illustrations.

How do we get started with Jetpack Compose?

· Installation: To begin, download the most recent version of Android Studio Arctic Fox, and create an app using the Empty Compose Activity template. The default template already contains some Compose elements.

· Composable Functions: Jetpack Compose is built around composable functions. These functions let you define your app’s UI programmatically by describing how it should look and providing data dependencies, rather than focusing on the process of the UI’s construction (initializing an element, attaching it to a parent, etc.). To create a composable function, just add the @Composable annotation to the function name.

· Layouts: UI elements are hierarchical, with elements contained in other elements. In Compose, you build a UI hierarchy by calling composable functions from other composable functions.

· Material Design: Compose is built to support material design principles. Many of its UI elements implement material design out of the box. In this lesson, you’ll style your app with material widgets.

· Lists and Animations: Lists and animations are everywhere in apps. In this lesson, you will learn how Compose makes it easy to create lists and fun to add animations.

Composable Functions

· Add a text element: First, we’ll display a “Hello world!” text by adding a text element inside the onCreate method. You do this by defining a content block, and calling the Text() function. The setContent block defines the activity's layout where we call composable functions. Composable functions can only be called from other composable functions. Jetpack Compose uses a Kotlin compiler plugin to transform these composable functions into the app's UI elements. For example, the Text() function that is defined by the Compose UI library displays a text label on the screen.

· Define a composable function: To make a function composable, add the @Composable annotation. To try this out, define a MessageCard() function which is passed a name, and uses it to configure the text element.

· Preview your Function in Android Studio: Android Studio lets you preview your composable functions within the IDE, instead of installing the app to an Android device or emulator. The composable function must provide default values for any parameters. For this reason, you can’t preview the MessageCard() function directly. Instead, let’s make a second function named PreviewMessageCard(), which calls MessageCard() with an appropriate parameter. Add the @Preview annotation before @Composable.

Rebuild your project. The app itself doesn’t change, since the new PreviewMessageCard() function isn't called anywhere, but Android Studio adds a preview window. This window shows a preview of the UI elements created by composable functions marked with the @Preview annotation. To update the previews at any time, click the refresh button at the top of the preview window.

Layouts

· Add Multiple Texts: So far we’ve built our first composable function and preview! To discover more Jetpack Compose capabilities, we’re going to build a simple messaging screen containing a list of messages that can be expanded with some animations.
Let’s start by making our message composable richer by displaying the name of its author and a message content. We need first to change our composable parameter to accept a Message object instead of a String, and add another Text composable inside the MessageCard composable. Make sure to update the preview as well:

This code creates two text elements inside the content view. However, since we haven’t provided any information about how to arrange them, the text elements are drawn on top of each other, making the text unreadable.

· Using a Column: The Column function lets you arrange elements vertically. Add Column to the MessageCard() function.
You can use Row to arrange items horizontally and Box to stack elements.

· Add an Image Element: Let’s enrich our message card by adding a profile picture of the sender. Use the Resource Manager to import an image from your photo library or use this one. Add a Row composable to have a well structured design and an Image composable inside it:

· Configure your layout: Our message layout has the right structure but its elements aren’t well spaced and the image is too big! To decorate or configure a composable, Compose uses modifiers. They allow you to change the composable’s size, layout, appearance or add high-level interactions, such as making an element clickable. You can chain them to create richer composables. Let’s use some of them to improve the layout:

Material Design

· Use Material Design: Our message design now has a layout, but it doesn’t look too good yet.

Jetpack Compose provides an implementation of Material Design and its UI elements out of the box. We’ll improve the appearance of our MessageCard composable using Material Design styling.

To start, we wrap our MessageCard function with the Material theme created in your project, ComposeTutorialTheme in this case. Do it both in the @Preview and in the setContent function.

Material Design is built around three pillars: Color, Typography, Shape. Let’s add them one by one.

Note: the Empty Compose Activity generates a default theme for your project that allows you to customize MaterialTheme. If you named your project anything different from MyApplication, you can find your custom theme in the ui.theme package.

· Color: Styling with colors from the wrapped theme is easy, and you can use values from the theme anywhere a color is needed.

Let’s style the title and add a border to the image:

· Typography: Material Typography styles are available in the MaterialTheme, just add them to the Text composables.

· Shape: With Shape we can add the final touches. We also add a padding to the message for a better layout.

· Enable Dark Theme: Dark theme (or night mode) can be enabled to avoid a bright display especially at night, or simply to save the device battery. Thanks to the Material Design support, Jetpack Compose can handle the dark theme by default. Having used Material colors, text and backgrounds will automatically adapt to the dark background.

You can create multiple previews in your file as separate functions, or add multiple annotations to the same function.

Let’s add a new preview annotation and enable night mode.

Color choices for the light and dark themes are defined in the IDE-generated Theme.kt file.

So far, we’ve created a message UI element that displays an image and two texts with different styles and it looks good both in light and dark themes!

Lists and Animations

· Create a List of Messages: A chat with one message feels a bit lonely, so let’s change our conversation to have more than one message. We need to create a Conversation function that will show multiple messages. For this use case, we can use Compose’s LazyColumn and LazyRow. These composables render only the elements that are visible on screen, so they are designed to be very efficient for long lists. At the same time, they avoid the complexity of RecyclerView with XML layouts.

In this code snippet, you can see that LazyColumn has an items child. It takes a List as a parameter and its lambda receives a parameter we’ve named message (we could have named it whatever we want) which is an instance of Message. In short, this lambda is called for each item of the provided List: Import this sample dataset into your project to help bootstrap the conversation quickly:

· Animate Messages while Expanding: Our conversation is getting more interesting. It’s time to play with animations! We will add the ability to expand a message to show a longer one, animating both the content size and the background color. To store this local UI state, we need to keep track of whether a message has been extended or not. To keep track of this state change, we have to use the functions remember and mutableStateOf.

Composable functions can store local state in memory by using remember, and track changes to the value passed to mutableStateOf. Composables (and its children) using this state will get redrawn automatically when the value is updated. We call this recomposition.

By using Compose’s state APIs like remember and mutableStateOf, any changes to state automatically update the UI:

Note: you will need to add the following imports to correctly use `by`. Alt+Enter will add them for you.

Now we can change the background of the message content based on isExpanded when we click on a message. We will use the clickable modifier to handle click events on the composable. Instead of just toggling the background color of the Surface, we will animate the background color by gradually modifying its valuefrom MaterialTheme.colors.surface to MaterialTheme.colors.primary and vice versa. To do so, we will use the animateColorAsState function. Lastly, we will use the animateContentSize modifier to animate the message container size smoothly:

Conclusion

Congratulations, you’ve finished the Compose tutorial! You’ve built a simple chat screen efficiently showing a list of expandable & animated messages containing an image and texts, designed using Material Design principles with a dark theme included and previews — all in under 100 lines of code!
Furthermore, if you have any more doubts you can reach out to me on LinkedIn

Here’s what you’ve learned so far:

· Defining composable functions

· Adding different elements in your composable

· Structuring your UI component using layout composables

· Extending composables by using modifiers

· Creating an efficient list

· Keeping track of state and modifying it

· Adding user interaction on a composable

· Animating messages while expanding them

Let’s keep sharpening our Kotlin and Jetpack Compose skills together!

--

--