Mobile Development 18 min read

Getting Started with Jetpack Compose: Overview, Setup, and Basic UI Components

This article introduces Jetpack Compose, Google's modern declarative UI toolkit for Android, covering its history, installation steps, adding Compose to existing projects or creating new ones, basic composable functions, layout techniques with Column, Container, Spacer, Material Design styling, and preview capabilities, all illustrated with Kotlin code examples.

Sohu Tech Products
Sohu Tech Products
Sohu Tech Products
Getting Started with Jetpack Compose: Overview, Setup, and Basic UI Components

At the recent Google I/O conference, Google unveiled Jetpack Compose, a new native Android UI framework that, like Apple's SwiftUI, adopts a declarative programming model, marking a full embrace of declarative UI on mobile platforms.

1. The History of Declarative UI

Declarative UI is not new; Microsoft introduced it in 2006 with WPF and XAML, supporting data binding and reusable templates. In 2010, Nokia's Qt team released Qt Quick (originally Qt Declarative) with QML, also offering data binding and JavaScript integration. Recent years have seen rapid growth, especially with React on the web and Flutter bringing the concept to mobile.

2. What is Jetpack Compose?

Jetpack Compose is a modern toolkit for building native Android UI using a declarative model. You describe the UI's appearance, and Compose automatically updates it when state changes. Built on Kotlin, it interoperates fully with Java and can coexist with existing Views, while providing built‑in Material components and animation support.

3. Environment Setup and Hello World

To get the best experience, install the latest Android Studio preview (Android Studio 4.0) which adds Compose templates and live preview.

There are two ways to start using Compose:

Add Compose to an existing project.

Create a new project that supports Compose.

3.1 Adding Compose to an Existing Project

Configure the required Gradle settings and dependencies:

(1) Gradle configuration

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"
    }
}

(2) Use the experimental Kotlin‑Gradle plugin

buildscript {
    repositories {
        google()
        jcenter()
        // To download the required version of the Kotlin‑Gradle plugin,
        // add the following repository.
        maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' }
    }
    ...
    dependencies {
        classpath 'com.android.tools.build:gradle:4.0.0-alpha01'
        classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.60-eap-25'
    }
}

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

(3) Add Compose toolkit dependencies

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'
    ...
}

3.2 Creating a New Compose Project

Select "Empty Compose Activity" when creating a new project; Android Studio will generate all required configuration automatically.

3.3 Hello World Example

In MainActivity.kt add the following code:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            Text("Hello, Android技术杂货铺")
        }
    }
}

Compose builds UI around composable functions. Adding the @Composable annotation turns a regular function into a composable element.

4. Layout Basics

UI elements are hierarchical. Use composable functions such as Column to arrange children vertically, similar to Flutter's Column widget.

@Composable
fun NewsStory() {
    Column {
        Text("我超❤️JetPack Compose的!")
        Text("Android技术杂货铺")
        Text("依然范特西")
    }
}

To add spacing, use HeightSpacer or WidthSpacer :

HeightSpacer(height = 20.dp)
WidthSpacer(width = 20.dp)

For more control, wrap content in a Container and set expanded or height properties:

@Composable
fun NewsStory() {
    val image = +imageResource(R.mipmap.header)
    Column(
        crossAxisSize = LayoutSize.Expand,
        modifier = Spacing(16.dp)
    ) {
        Container(expanded = true, height = 180.dp) {
            DrawImage(image)
        }
        HeightSpacer(height = 20.dp)
        Text("我超❤️JetPack Compose的!")
        Text("Android技术杂货铺")
        Text("依然范特西")
    }
}

5. Using Material Design

Compose integrates Material Design components out of the box. Apply MaterialTheme and style texts with predefined typographies:

@Composable
fun NewsStory() {
    val image = +imageResource(R.mipmap.header)
    MaterialTheme {
        Column(
            crossAxisSize = LayoutSize.Expand,
            modifier = Spacing(16.dp)
        ) {
            Container(expanded = true, height = 180.dp) {
                Clip(shape = RoundedCornerShape(10.dp)) {
                    DrawImage(image)
                }
            }
            HeightSpacer(height = 20.dp)
            Text("我超❤️JetPack Compose的!", style = +themeTextStyle { h5 })
            Text("Android技术杂货铺", style = +themeTextStyle { body1 })
            Text("依然范特西", style = +themeTextStyle { body2 })
        }
    }
}

You can also control opacity and max lines to handle long titles:

Text(
    "我超❤️JetPack Compose的!写起来简单,复用性又强...",
    maxLines = 2,
    overflow = TextOverflow.Ellipsis,
    style = (+themeTextStyle { h5 }).withOpacity(0.87f)
)

6. Real‑time Preview

Starting with Android Studio 4.0, you can preview composable functions directly in the IDE by annotating them with @Preview . The preview updates instantly when the layout changes, and multiple composables can be previewed simultaneously.

7. Conclusion

Jetpack Compose is still in preview, so it may not be ready for production use, but it offers a powerful declarative approach to Android UI development. Together with React, Flutter, and SwiftUI, declarative UI is becoming the mainstream way to build modern user interfaces.

AndroidKotlinDeclarative UIJetpack ComposeMaterial DesignUI Layout
Sohu Tech Products
Written by

Sohu Tech Products

A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.