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.
This feature is currently in alpha version but we really need to think about it this early.
Jetpack compose is currently present in Android Studio 4.0 and above which is in the canary build which means currently there might be some bugs in it and shouldn’t be used in the production version of the apps.
Some configuration changes needed to use Jetpack Compose
You need to set your app’s minimum API level to 21 or higher and enable Jetpack Compose in your app’s build.gradle
file, as shown below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
android { defaultConfig { ... minSdkVersion 21 } buildFeatures { // Enables Jetpack Compose for this module compose true } ... // Set both the Java and Kotlin compilers to target Java 8. compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = "1.8" } } |
Jetpack Compose currently requires an experimental version of the Kotlin-Gradle plugin. To include this plugin in your app, include the following dependencies in your project’s build.gradle
file:
1 2 3 4 |
dependencies { classpath 'com.android.tools.build:gradle:4.0.0-alpha01' classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.60-eap-25' } |
Include Jetpack Compose toolkit dependencies in your app’s build.gradle
file, as shown below:
1 2 3 4 5 6 7 |
dependencies { // You also need to include the following Compose toolkit dependencies. implementation 'androidx.ui:ui-tooling:0.1.0-dev02' implementation 'androidx.ui:ui-layout:0.1.0-dev02' implementation 'androidx.ui:ui-material:0.1.0-dev02' ... } |
A simple Compose App: Hello World
Let’s take a look at the code needed for a simple “Hello World” app with Jetpack Compose.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class ComposeActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { CraneWrapper { MyApp() } } } @Composable fun MyApp() { MaterialTheme { Text(text = "Hello world!", style = +themeTextStyle { h3 }) } } } |
In the onCreate
method we set the content of our Compose app by calling setContent
. This is a method that initializes the composable widget tree and wraps it in a FrameLayout
.
To make things work we need to wrap our app in a CraneWrapper
and MaterialTheme
. CraneWrapper
is responsible for setting up providers for the Context
, FocusManager
and TextInputService
. The MaterialTheme
is needed to provide colors, styles, and fonts to your widgets. With this in place, we can add a Text
component that will render our text on the screen in a certain style.