now let's get to the most exciting part. start writing code in the editor.
code example:
small guide and theory
Jetpack Compose Quick Guide
Jetpack Compose is a modern, fully declarative UI toolkit for building native Android applications. It allows you to define UI components using Kotlin code, eliminating the need for XML layouts.
1. Setting Up Jetpack Compose
First, make sure you have the required dependencies in your build.gradle
files.
Project-level build.gradle
Copy buildscript {
ext {
compose_version = '1.5.0'
}
dependencies {
classpath "androidx.compose:compose-gradle-plugin:$compose_version"
}
}
App-level build.gradle
Copy plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
id 'androidx.compose'
}
android {
compileSdk 33
defaultConfig {
applicationId "com.example.composeapp"
minSdk 21
targetSdk 33
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
composeOptions {
kotlinCompilerExtensionVersion '1.5.0'
kotlinCompilerVersion '1.8.10'
}
}
dependencies {
implementation "androidx.compose.ui:ui:$compose_version"
implementation "androidx.compose.material3:material3:$compose_version"
implementation "androidx.compose.ui:tooling-preview:$compose_version"
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.5.0"
implementation "androidx.activity:activity-compose:1.5.0"
// other dependencies
}
2. Basic Structure
In Jetpack Compose, UI is defined using composable functions. These functions are marked with the @Composable
annotation and describe the UI components.
Creating a Simple Composable
A basic composable function could look like this:
Copy @Composable
fun Greeting(name: String) {
Text(text = "Hello, $name!")
}
You can use the Greeting
composable in your setContent
block like this:
Copy @Composable
fun MyApp() {
Greeting(name = "John")
}
Main Activity Setup
In the MainActivity
, you typically use setContent
to set the initial UI.
Copy class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyApp()
}
}
}
3. Common UI Elements
Jetpack Compose provides a wide variety of UI elements (composables). Below are some of the most common ones.
Text
Copy @Composable
fun MyText() {
Text(text = "Welcome to Jetpack Compose!")
}
Button
Copy @Composable
fun MyButton() {
Button(onClick = { /* Handle click */ }) {
Text(text = "Click Me")
}
}
Image
Copy @Composable
fun MyImage() {
Image(painter = painterResource(id = R.drawable.my_image), contentDescription = null)
}
Column and Row
Column
and Row
are layout composables used to organize UI elements vertically and horizontally.
Copy @Composable
fun MyColumn() {
Column {
Text(text = "First Item")
Text(text = "Second Item")
}
}
@Composable
fun MyRow() {
Row {
Text(text = "Left Item")
Text(text = "Right Item")
}
}
Modifier
Modifiers allow you to style and adjust the layout of your composables.
Copy @Composable
fun StyledButton() {
Button(
onClick = { /* Handle click */ },
modifier = Modifier.padding(16.dp).fillMaxWidth()
) {
Text(text = "Styled Button")
}
}
4. Handling State
Jetpack Compose is declarative, meaning UI updates are tied to changes in state. You manage state using state variables and composable functions.
State with remember
Copy @Composable
fun Counter() {
var count by remember { mutableStateOf(0) }
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxSize()
) {
Text(text = "Count: $count")
Button(onClick = { count++ }) {
Text(text = "Increment")
}
}
}
In this example, the state of count
is remembered across recompositions, and the UI updates when count
changes.
5. Navigation
Jetpack Compose offers an easy way to handle navigation between different screens.
Navigation Setup
You need to include the navigation library in your dependencies:
Copy dependencies {
implementation "androidx.navigation:navigation-compose:2.5.0"
}
Basic Navigation Example
Copy @Composable
fun FirstScreen(navController: NavController) {
Button(onClick = {
navController.navigate("second_screen")
}) {
Text("Go to Second Screen")
}
}
@Composable
fun SecondScreen() {
Text("This is the second screen!")
}
@Composable
fun NavigationGraph(navController: NavController) {
NavHost(navController, startDestination = "first_screen") {
composable("first_screen") { FirstScreen(navController) }
composable("second_screen") { SecondScreen() }
}
}
In the MainActivity
, set up the NavController
:
Copy @Composable
fun MyApp() {
val navController = rememberNavController()
NavigationGraph(navController)
}
6. Theming and Material Design
Jetpack Compose integrates well with Material Design. You can define themes for your app using MaterialTheme
.
Customizing the Theme
Copy @Composable
fun MyCustomTheme(content: @Composable () -> Unit) {
MaterialTheme(
colorScheme = lightColorScheme(
primary = Color(0xFF6200EE),
secondary = Color(0xFF03DAC6)
),
typography = Typography,
content = content
)
}
@Composable
fun AppContent() {
MyCustomTheme {
// Your UI components here
Greeting(name = "World")
}
}
7. Previewing UI
Jetpack Compose supports previewing UI directly in Android Studio. You can add a preview function like this:
Copy @Preview(showBackground = true)
@Composable
fun DefaultPreview() {
MyApp()
}
This allows you to view the UI without running the app on an emulator or device.