Jetpack Compose, how to start with it and develop an application

Muhammed Salih Guler
ProAndroidDev
Published in
12 min readAug 7, 2020

--

As time goes by, technologies evolve and try to offer a better experience to developers for developing their applications. For example, in the earlier stages of Android, it was pretty common to use EventBus to send data through the app, and Mosby to implement the Model-View-Presenter pattern. Nowadays, they are far from being the most common way to develop applications. It is more common to use the MVVM pattern using AndroidX libraries implemented and recommended by the Android team.

The Android team not only presents and suggests logical patterns, but they are also working on how you implement the UI for the application as well. Right now, Android is heavily using Imperative UI pattern by using XML (Extensible Markup Language) files. Reaching to UI elements is possible by using findViewById() method. Once the view is retrieved, you can update the properties of it or invoke its methods. This approach is great and loved by a lot of developers but as Android development shifted towards a more reactive programming approach, the benefits of the imperative approach started to shrink. Therefore the Android team decided to use a different pattern called Declarative UI pattern. With Declarative UI, developers are declaring what the UI looks like by describing the views and their properties. The UI has a state and each time the state changes, the UI updates and recreates it’s UI elements.

After they decided to use the Declarative UI pattern, the Android team wanted to prevent one mistake that they have done before. The UI implementation was finding its place next to the Android platform code. That meant, the releases were less frequent and when an error happened it required a bigger release on the Android OS. That’s why the Android team decided to release this new UI approach as a library.

The Android team was working on a set of libraries called Jetpack which is a suite of libraries to help developers follow best practices, reduce boilerplate code, and write code that works consistently across all Android versions. Therefore putting this new UI library into this was the best decision they could make. And this is how Jetpack Compose was born.

Jetpack Compose is Android’s modern toolkit for building native Android applications. Jetpack Compose simplifies and accelerates UI development on Android. It does more with less code and avoids entire classes of bugs, so code is simple and easy to maintain. Every time the state changes, the UI automatically gets updated. It is compatible with all your existing code so you can adopt when and where you want.

This article was first published in Codemagic blog.

Get Started

Jetpack Compose is a preview feature, and support for Compose is included only in Canary versions of Android Studio and you need to download it. At this date, the latest version of Android Studio is version 4.2 Canary 5 and version of Jetpack Compose is 0.1.0-dev14.

After you downloaded Android Studio’s Canary version, just follow the instruction steps from the installer to be able to install Android Studio. You are not going to learn the Android Studio installation here but, if you are feeling lost, please refer to the document here.

About the app

Today you will be creating a simple Popular Movies application. The application will have some information provided locally by the TMDb API for Popular Movies. The app will show these movies as a list in the application.

Creating the project

For creating a Jetpack Compose project, you can start by clicking on Create New Project button on the opened dialog. Once you click on it, you will see a window like below.

As you see from the picture above, you can see multiple project templates. Whatever project type you need for any Android-based OS, you can find a template for it. For our project pick Empty Compose Activity and move to the next window.

In the window above, you will be asked to add some information about your application. Let’s go over the field one by one:

- Name: Name of the application

- Package name: Unique identifier for your application. Mainly a domain name for your company and the name of the application

- Save location: Location of the app directory

- Language: Programming language to be used in the application. In the classic approach, you can have either Java or Kotlin but with Compose, you need to use Kotlin.

- Minimum SDK: Minimum SDK version supported by the application.

Once you input and select the correct information, click on the Finish button to set up your application. After the setup, you will see the main project window like below.

Project Window

The project window that you see above will be your main workplace. You can see three main project windows. Let’s learn about the most important ones in detail.

Project Pane

Your main focus area will be under the app folder. app/build.gradle is your project’s Gradle file. This file is used to define information about your application and to declare libraries used. The application’s source code will be mainly located in the app/src/ folder.

app/src/androidTest and app/src/test folders will be the dedicated folders for testing. Your application will be lying under app/src/main/ folder. Your resources will be under the res folder and your code will be under java/your_app_identifier.

Code Pane

Code pane will be the view that you will be working most of the time. The code you are writing will be shown there. You will learn the code part in detail soon.

Live Preview

With the classical Android approach, you were mostly able to see your layout in the layout view. This was giving you a chance to see your changes directly. Jetpack Compose came with a great tool called Live Preview to give you the same feeling.

Once you create your application, you need to run your application at least once. After you run it, the Live Preview will be ready for your usage.

Whenever you make a change your changes will be built and drawn into Live Preview. When you make a lot of changes there might be times that you need to restart your Live Preview but it is not something taking a long time.

After you see the live preview, you will see some buttons. Those buttons will help you to do multiple operations e.g. Deploying changes to device, Enabling Live Preview to be clickable, and many more.

Now that you got to know your IDE, it’s time to dive deep into code.

Let’s see the code

When you create the application, it will create a simple project for you.

Activity creation and its life cycle elements are created as it was before. In the classic Android development approach, you should have called setContentView to get the reference to the view. With Jetpack Compose, you need to use the setContent method to compose your application.

In Jetpack Compose, each function that is defined to create a UI content is a Composable. Composable functions are the fundamental building blocks of an application built with Compose. You can use either existing Composable functions or create your Composable functions by combining multiple Composable functions by using @Composable annotation.

PopularMoviesTheme above is the top-level Composable function that keeps the theme information. Just like the other UI elements, the theme information is also a Composable function. It decides on the color palette according to system information. The function also accepts a Composable function as a child element.

Greeting is your content to be shown on the screen. It is also a Composable function. It uses one of the many out-of-box Composable functions from the library.

You learned about Live Preview, but you haven’t seen any sign of it. To use Live Preview, you need to add the @Preview annotation to your Composable function. You can modify the attributes of the @Preview annotation. e.g. showBackground will show a background filling.

If you run the app on an emulator, now you can see the view below.

Working on the Popular Movies App

Building the basics

As first step, you will remove the Greeting and DefaultPreview functions and create your Composable function.

With the code above, you will create PopularMoviesMainPage the UI elements on the page. As the base UI element, you will use a Composable function called Column. Column is used for placing its children in a vertical sequence. If you want to go for a horizontal sequence, you should use Row. For both of them, you can just put one element after another by writing one Composable function after another.

The next step is to create an app bar on the top of the screen. For that, you need to use a Composable function called TopAppBar. TopAppBar displays information and actions relating to the current screen and is placed at the top of the screen. It has multiple attributes that you can use to change the look of the app bar. You can define backgroundColor, contentColor, navigationIcon and many more other attributes for the TopAppBar.

The final step for this part is to generate a list of 100 elements to just demonstrate the scrollable view. For this purpose, you will be using AdapterList Composable function. AdapterList is a vertically scrolling list that only composes and lays out the currently visible items. It will ask you to provide a list of data for representing on the screen.

If you put them together, as below, you will see the desired screen as follows.

Creating a Movie list and showing basic information

To create a movie list, you will download the information from TMDb and store them locally. Since this is a bit on the beginner side, network communications will be handled in the other articles.

To store the information about movies, you will create a Kotlin data class called Movie. For that, right-click on the app/src/main/java/your_package_name/ and create a new folder called data. Under data create a new Kotlin file and call it Movie.kt and paste the code from below.

The code above is a simple data class keeping information about the movie. All the fields will keep information with the related type of data, only exception is image. image will keep the id reference of the resource in your project. Now that you have the movie data holder, let’s feed some information into it.

Under the same folder, create a file called MovieData.kt. In this file, you will be creating your movie information.

For feeding the movie information, paste the code below.

The MovieData is an object to help us to reach out to the movie related data. list variable in the object is keeping the information about the movies and to use this list, you can simply write MovieData.list.

Now let’s get back to MainActivity.kt file and update your Composable functions.

First of all, change the following part:

to the following part:

Once you do that, you will see that the compiler will be complaining about PopularMoviesListItem since you have not created it yet. This will be your new Composable function to show movie information.

You can satisfy the compiler by adding the following code.

With the code above, you are just adding the movie title to a text. You will also use modifier to add some padding. But, what is Modifier? A modifier is an ordered, immutable collection of elements that decorate or add behavior to Compose UI elements like backgrounds, padding, click event listeners, and many more.

If you run the application now, you will see the following in your emulator.

Create beautiful list items

So far you have implemented the data and the information you can use to create a movie list. But unfortunately, your list items don’t look that amazing at the moment. But don’t worry, you will tackle that now.

For the list item, you will be only working on the PopularMoviesListItem Composable function you created. First of all, let’s start by wrapping the title with a Card. A Card will give the user a more independent feeling about the item and you can encapsulate all movie information per item.

Card has a lot of attributes that you can use. To have a rounded shape (or any other shape), you can use the shape attribute. For the card’s general UI specifications you will use the modifier attribute. This way you will handle padding, width, and height for the card.

Card will accept one child under it to show information. You will move your Text inside it as shown above. If you run the app now, you will see the following.

Since you want to show multiple information on the card and you already learned that Card is accepting only one child. For this purpose, you will use the Column.

As the next step, you will add the movie image to the list. To add an image, you will use the Image Composable function. Image is a composable that lays out and draws a given image asset. The asset property is used to provide an image resource. imageResource function will accept the id of the image and provide the ImageAsset for the view. Image also has a lot more properties for scaling, aligning, and changing the UI representation of the image. With your example, you will set your height to a specific height. Also, you will tell the image to be as big as the width by using the contentScale property. To align the image, the alignment property is used. The default alignment is centered, you will move that to top.

To have a nicer UI, you will change the size of the Text for the movie title. For that purpose, you will use the style property and use the typography that has been provided by the MaterialTheme itself.

If you update your Column as following, you will start to see the image and title of the movie more nicely.

And your app now looks like the following:

Now last but not least, let’s add the rest of the movie information to the screen. Let’s continue with adding the release date and vote for the movies. You will add them in the same horizontal direction and, since it is in the horizontal direction, you will use Row.

If you see the code above, the only new and shiny part is the horizontalArrangement property for Row. horizontalArrangment is the horizontal arrangement of the layout’s children. You can have the children aligned with equal gaps, put the child elements around the whole horizontal UI component, or simply put them so the child elements can share the same space in the horizontal UI component.

Let’s add the overview information for the movie to the end and wrap it up.

The Text Composable function has a lot of useful properties. Since the overview can be longer for some movies, it makes sense to limit the maximum lines of texts. For that, you will be using maxLines property. But, when you limit the lines, you do not want to cut off the text, it’s more logical to show the at the end, so users can understand what is going on. For that, you will be using overflow property and change it to TextOverflow.Ellipses. Once you are done with it, let’s run and see how your app looks like!

Conclusion

Jetpack Compose is still young and actively developed. Therefore, a lot can change along the way. But, if you are into Declarative UI patterns it is something you would like to try out.

p.s. If you are a Flutter developer like me, you will not have any hard time to use it.

Resources

Written Content

- Jetpack Compose home page

- Jetpack Compose on Android Studio

- Jetpack Compose Tutorial from Google

- Jetpack Compose Codelab from Google

- JetNews: A Jetpack Compose app from Google

- Compose Release Notes

Video Content

- What’s New in Jetpack Compose (Android Dev Summit ‘19)

- Understanding Compose (Android Dev Summit ‘19)

Project files

Click here to download the whole project as a zipped folder.

This article was first published in Codemagic blog.

--

--