pen-to-squareEditor

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

App-level build.gradle

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:

You can use the Greeting composable in your setContent block like this:

Main Activity Setup

In the MainActivity, you typically use setContent to set the initial UI.


3. Common UI Elements

Jetpack Compose provides a wide variety of UI elements (composables). Below are some of the most common ones.

Text

Button

Image

Column and Row

Column and Row are layout composables used to organize UI elements vertically and horizontally.

Modifier

Modifiers allow you to style and adjust the layout of your composables.


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

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.

You need to include the navigation library in your dependencies:

Basic Navigation Example

In the MainActivity, set up the 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


7. Previewing UI

Jetpack Compose supports previewing UI directly in Android Studio. You can add a preview function like this:

This allows you to view the UI without running the app on an emulator or device.


Last updated