Getting started with Jetpack Compose

Live Preview

So, maybe you’ve heard about Jetpack Compose but haven’t checked it out, or you haven’t heard about it at all. Jetpack Compose is a modern toolkit for building native Android UI. It’s based on the declarative programming model, so you can simply describe what your UI should look like, and Compose takes care of the rest—as app state changes, your UI automatically updates. Sounds cool right?

Okay. Let me put it in a different way. Imagine a situation whereby you are given the ability to describe how you want your UI to look like and then Compose takes care of rendering it for you, just like you want! No layout file. No extra language to build your layout with.

Jetpack Compose is compatible with the existing UI toolkit, meaning you can integrate it with your existing project. It is designed with Material and animations from the start, to give your app a more appealing look.

As of today, Jetpack Compose is still new, not stable yet and isn’t ready for production yet, so changes are inevitable and expected. However, it keeps evolving and the team is still working on it.

Requirements

Here are some of the requirements to get started with Jetpack Compose:

  • Latest Version of Android Studio (>= v4.0)
  • Minimum API level 21
  • Kotlin-Gradle experimental plugin

That’s pretty much it.

Luckily, once you have the latest version of Android Studio downloaded, some of these would be handled already for you.

Getting Started

Head over here to download the latest version (4.0) of Android Studio. You can install it side by side your presently installed stable Android Studio version or have a clean install.

Once you are done installing, you can proceed to the following steps to create a new project that includes Jetpack Compose:

1. If you’re in the Welcome to Android Studio window, click Start a new Android Studio project. If you already have an Android Studio project open, select File > New > New Project from the menu bar.

2. In the Select a Project Template window, select Empty Compose Activity and click Next.

3. In the Configure your project window, do the following:

  • Set the NamePackage name, and Save location as you normally would.
  • Note that, in the Language dropdown menu, Kotlin is the only available option because Jetpack Compose works only with classes written in Kotlin.
  • In the Minimum API level dropdown menu, select API level 21 or higher.

4. Click Finish.

New Jetpack Compose Project

If you have everything set up right as described above, you should have your project built and you should be good to go.

What can you notice?

Let us take a look at some vital things Android Studio has helped us set up in our project before we proceed to check up our new UI toolkit.

Gradle Configuration

Open your app’s build.gradle file, you should see something similar to what is shown below:

android {
    defaultConfig {
        ...
        minSdkVersion 21
    }

    buildFeatures {
        // Enables Jetpack Compose for this module
        compose true
    }
    ...

// To inline the bytecode built with JVM target 1.8 into
// bytecode that is being built with JVM target 1.6. (e.g. navArgs)

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = "1.8"
    }
}

Notice Android Studio has helped us to set minSdkVersion to 21. Also compose is set to true to enable Jetpack Compose for our project module. The rest of the code is to set both the Java and Kotlin compilers to target Java 8.

Experimental Kotlin-Gradle plugin

Open your app’s build.gradle file, you should see something similar to what is shown below:

buildscript {
    ext.kotlin_version = '1.3.60-eap-25'
    repositories {
        google()
        jcenter()
        maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:4.0.0-alpha02'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' }
    }
}

Because Jetpack Compose currently requires an experimental version of the Kotlin-Gradle plugin, Android Studio automatically set that up for us.

Jetpack Compose toolkit dependencies

Open your app’s build.gradle file, and in the dependencies section, you should see something similar to what is shown below:

dependencies {
    ...
    implementation 'androidx.ui:ui-layout:0.1.0-dev02'
    implementation 'androidx.ui:ui-material:0.1.0-dev02'
    implementation 'androidx.ui:ui-tooling:0.1.0-dev02'
    ...
}

Jetpack Compose requires a couple of toolkit dependencies. Luckily, Android Studio gets that set up for us also.

That’s all for our setup. Let’s go over to actual code.

Composition

Open your MainActivity.kt file, and in your onCreate() function, you should see something similar to this:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
        MaterialTheme {
            Greeting("Android")
        }
    }
}

There is a setContent function that takes in some other function that takes in another function. Don’t worry it’s not complicated. Let’s take a look into the source code for the setContent function.

fun Activity.setContent(
    content: @Composable() () -> Unit
): CompositionContext? {
    val composeView = window.decorView
        .findViewById<ViewGroup>(android.R.id.content)
        .getChildAt(0) as? AndroidComposeView
        ?: AndroidComposeView(this).also { setContentView(it) }

    ...
}

setContent is essentially an extension function of the Activity class. It takes in a composable function (we are getting there soon) and composes the given composable function into the given activity. The composable will become the root view of the given activity.

What are composable functions?

Jetpack Compose is built around composable functions. These functions let you define your app’s UI programmatically by describing its shape and data dependencies, rather than focusing on the process of the UI’s construction. And to create a composable function, just add the @Composable annotation to the function name.

The MaterialTheme composable function defines the styling principles for our app and can take in other composable functions.

Greeting is a composable function (not in-built) as you can see below the MainActivity class, that takes in a param name and creates a Text component using the parameter passed into the Greeting function.

@Composable
fun Greeting(name: String) {
    Text(text = "Hello $name!")
}

Text also, is a composable function (in-built) that defines a set of customizations for how our text should look like, as seen below:

@Composable
fun Text(
    text: String,
    modifier: Modifier = Modifier.None,
    style: TextStyle? = null,
    paragraphStyle: ParagraphStyle? = null,
    softWrap: Boolean = DefaultSoftWrap,
    overflow: TextOverflow = DefaultOverflow,
    // TODO(siyamed): remove suppress
    @SuppressLint("AutoBoxing")
    maxLines: Int? = DefaultMaxLines,
    selectionColor: Color = DefaultSelectionColor
) {
    Text(
        text = AnnotatedString(text),
        modifier = modifier,
        style = style,
        paragraphStyle = paragraphStyle,
        softWrap = softWrap,
        overflow = overflow,
        maxLines = maxLines,
        selectionColor = selectionColor
    )
}

At this point, it is important to note a few things:

  • Composable functions can only be called from within the scope of other composable functions.
  • Composable functions are essentially created outside the class body. This makes them easily accessible anywhere in the project.

Live Previews

Live previews is an Android Studio feature that allows you to test and compare your app’s composable functions across various orientations, font sizes, and themes—without having to deploy your app. In other words, Live Preview, just like the regular preview screen for your XML layouts, enables you to preview your composable functions easily without having to run your app on an emulator first.

Live Preview is generated by a composable function with an extra @Preview annotation. Let’s take a look at how this is done in our project:

@Preview
@Composable
fun DefaultPreview() {
    MaterialTheme {
        Greeting("Android")
    }
}

This function instructs our preview screen to display the composed view from our Greeting function, using the MaterialTheme. On the right side of your Android Studio, you should see something similar to this:

Live Preview

Now let’s change the parameter for our Greeting function from Android to World, in our DefaultPreview function. Do the same in the setContent function also, as we will be running the app soon and this is what will reflect on the app.

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MaterialTheme {
                Greeting("World")
            }
        }
    }
}

@Composable
fun Greeting(name: String) {
    Text(text = "Hello $name!")
}

@Preview
@Composable
fun DefaultPreview() {
    MaterialTheme {
        Greeting("World")
    }
}

On the top right of the preview screen, click on the Build & Refresh button to refresh the preview. If all goes well, you should the text change in the preview, just like this:

Hello World Live Preview

If you see that, then you’ve been doing everything right. You deserve a prize!

Now, let’s test our app on an emulator. Click on the run button to launch an emulator. If all goes well, you should see this displayed:

First Jetpack App

Yay! We just created our first Jetpack compose app with few lines of code. Pretty easy right?

excited dance GIF

How about we quickly try a wordplay? Say after me:

I, a composer, am composing some views using composable functions, enabled by Jetpack compose and that, is called composition.

Emmanuel Kehinde, 2019

Sounds cool yeah? ?


Now that you have been introduced to Jetpack compose, don’t stop there. Get your hands dirty. Try it out. Check out Jetpack compose basics tutorial provided by Google and also the Jetpack compose basics codelab.

Can’t wait to hear you share your experience with Jetpack compose!