Getting Started With Compose
Jetpack Compose is a new way of designing native Android apps using Kotlin, No more XML.
For the best experience developing with Jetpack Compose, you should download the latest canary version of Android Studio Preview. That’s because when you use Android Studio to develop your app with Jetpack Compose, you can benefit from smart editor features, such as New Project templates and the ability to immediately preview your Compose UI.
Alternatively, you can just upgrade your existing Android Studio
Starting
Open the starter project on your android studio and after building it you should see a hello world text on the screen.
Setting dependencies
In your app/build.gradle file under dependencies
block add the following dependencies
dependencies {
implementation("androidx.compose.ui:ui:1.1.1")
// Tooling support (Previews, etc.)
implementation("androidx.compose.ui:ui-tooling:1.1.1")
// Foundation (Border, Background, Box, Image, Scroll, shapes, animations, etc.)
implementation("androidx.compose.foundation:foundation:1.1.1")
// Material Design
implementation("androidx.compose.material:material:1.1.1")
// Material design icons
implementation("androidx.compose.material:material-icons-core:1.1.1")
implementation("androidx.compose.material:material-icons-extended:1.1.1")
// Integration with observables
implementation("androidx.compose.runtime:runtime-livedata:1.1.1")
implementation("androidx.compose.runtime:runtime-rxjava2:1.1.1")
// UI Tests
androidTestImplementation("androidx.compose.ui:ui-test-junit4:1.1.1")
}
Keep in mind Compose isn’t just one library that you import, it includes different libraries for different UI constructs you may want to use.
In addition to those dependencies, you can see that the compose
flag is set to true
, in the buildFeatures
block within android
:
buildFeatures {
compose true
}
Time to code
Open MainActivity.kt and replace the existing call to setContentView()
with the following:
setContent {
Text("Hello, World!")
}
In addition to setContent()
, there’s another new player in town in the above code snippet: Text()
.
In Jetpack Compose, you use methods marked with the @Composable
annotation to build your UI. This is demonstrated below:
@Composable
fun Text(
...
)
Text()
composable is in charge of, you guessed it, drawing text on the screen. You can think of it as being the Compose version of a TextView
.
Build the project to preview what you’ve done
You can customize your text by using a TextStyle
. Try it out by replacing the existing Text()
one with the following:
Text("Hello, World!", style = TextStyle(color = Color.Red))
We will continue on the next article