Android Jetpack Compose – Build Native UIs with Kotlin - Textnotes

Android Jetpack Compose – Build Native UIs with Kotlin


Learn how to build native Android UIs using Jetpack Compose, a modern declarative UI toolkit in Kotlin. This tutorial covers the basics of Jetpack Compose, its benefits over XML, and how to start building your UI using Kotlin code.

Jetpack Compose is a modern toolkit introduced by Google for building native Android UIs. Unlike the traditional XML-based approach, Jetpack Compose allows developers to define UIs using Kotlin code in a declarative style, making UI development simpler, more intuitive, and easier to maintain.

In this tutorial, we will explore Jetpack Compose and its core features, starting from setting up a project to building a simple UI.

i) What is Jetpack Compose?

Jetpack Compose is a UI toolkit for building Android applications using Kotlin. It eliminates the need for writing XML layouts and enables a declarative approach to UI development.

With Jetpack Compose, the UI components are described in Kotlin functions rather than XML files. This makes UI development more flexible and easier to manage, especially for dynamic and complex UIs.

1. Benefits of Jetpack Compose:

  1. Declarative UI: Define UI in Kotlin code, which is more intuitive and easier to understand compared to XML.
  2. Less Boilerplate: Write fewer lines of code and eliminate XML-related boilerplate code.
  3. State Management: Compose is designed to handle dynamic state, making it easier to manage UI states.
  4. Seamless Integration: Jetpack Compose integrates well with existing Android Views and works alongside other Jetpack libraries.
  5. Less Complexity: Use Kotlin's concise syntax and powerful features, making code more readable and maintainable.

ii) Setting Up Jetpack Compose in Android Studio

1. Prerequisites:

  1. Android Studio Arctic Fox or later (Jetpack Compose is fully supported from version 2020.3.1).
  2. Kotlin enabled in your project.

2. Create a New Project with Jetpack Compose:

  1. Open Android Studio and select New Project.
  2. Choose the Empty Compose Activity template.
  3. Make sure to select Kotlin as the programming language.
  4. Click Finish to create the project.

Android Studio will automatically set up everything you need for Jetpack Compose, including dependencies.

3. Add Compose Dependencies:

Ensure that the necessary Jetpack Compose dependencies are added in your build.gradle files.

In your app-level build.gradle file, add the following dependencies:


android {
compileSdk 31

defaultConfig {
applicationId "com.example.jetpackcompose"
minSdk 21
targetSdk 31
}

buildFeatures {
compose true
}

composeOptions {
kotlinCompilerExtensionVersion '1.0.3'
kotlinCompilerVersion '1.5.31'
}

dependencies {
implementation "androidx.compose.ui:ui:1.0.3"
implementation "androidx.compose.material:material:1.0.3"
implementation "androidx.compose.ui:ui-tooling-preview:1.0.3"
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.3.1"
implementation "androidx.activity:activity-compose:1.3.1"
}
}

After adding the dependencies, sync the project to ensure everything is set up correctly.

iii) Declarative UI in Jetpack Compose

In Jetpack Compose, the UI is described using Kotlin functions. Here, you describe what the UI should look like based on the current state of the application, and Jetpack Compose automatically updates the UI when the state changes.

1. Basic Example – Hello World in Compose:

Here’s a simple example of how to create a basic UI in Jetpack Compose using Kotlin code.


import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview

class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Greeting("Android Developer")
}
}
}

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

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
Greeting("Preview")
}

In this code:

  1. @Composable is an annotation that marks a function as a composable function (a function that can be used to create UI components).
  2. Greeting is a composable function that takes a name argument and displays a greeting message.
  3. setContent is used in the onCreate() method to set the content of the activity with a composable function.
  4. @Preview allows us to preview the composable function in the Android Studio design editor.

2. Composables: Building Blocks of UI

A composable is the fundamental building block of Jetpack Compose UIs. Composables are functions that describe part of your UI, like Text, Button, Image, and more.

Example:

@Composable
fun MyApp() {
Column {
Text("Welcome to Jetpack Compose")
Button(onClick = { /* Handle Click */ }) {
Text("Click Me")
}
}
}

In this example:

  1. Column is a composable that arranges child elements vertically.
  2. Text is used to display text.
  3. Button is a clickable element that triggers actions when clicked.

The UI is described directly in Kotlin, unlike the traditional XML approach, where you would have to define a Button, TextView, etc., in separate XML layout files.

iv) Jetpack Compose vs XML (Declarative vs Imperative)

1. Traditional XML (Imperative UI)

In the traditional XML-based approach, you define the UI in XML layout files, and then interact with the views in your Activity or Fragment. The UI is constructed in an imperative way, meaning you have to tell the app how to create the UI and update it.


<!-- XML Layout -->
<Button
android:id="@+id/button"
android:text="Click me"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

2. Jetpack Compose (Declarative UI)

In Jetpack Compose, you describe what the UI should look like, and Compose takes care of updating the UI when the state changes. It’s a declarative approach, meaning you describe the UI as a function of the current app state.


// Composable Function in Kotlin
@Composable
fun ButtonExample(onClick: () -> Unit) {
Button(onClick = onClick) {
Text("Click Me")
}
}

3. Key Differences:

  1. Declarative (Compose): You describe the UI state and the framework updates it for you. It’s more intuitive and flexible.
  2. Imperative (XML): You define the UI structure in XML and then write imperative code to update the UI.

v) Conclusion

Jetpack Compose simplifies the process of building native Android UIs with Kotlin. It introduces a declarative approach, where you describe the UI, and Jetpack Compose takes care of the UI updates.

Key takeaways from this tutorial:

  1. Declarative UI is more flexible and reduces boilerplate code.
  2. Composables are the building blocks of Jetpack Compose UIs, similar to XML views in traditional Android development.
  3. Jetpack Compose integrates well with existing Android views and supports the modern Kotlin language features.

By adopting Jetpack Compose, you can simplify your Android UI development, make your code more readable, and ensure better maintainability for your apps.