Jetpack Compose is a new toolkit that takes a declarative UI approach for building native Android interfaces.

Download the latest version of AndroidStudio

To develop Jetpack Compose, use the latest Canary preview version of Android Studio. When developing your app with Android Studio and Jetpack Compose, you can benefit from smart editor features such as the “New Project” template and instant preview of the Compose interface.

Two: Create a new Jetpack Compose sample application

After downloading AndroidStudio, you can go to AndroidStudio->File->New Project-> Empty Compose Activity->Next->Finish. Note: The new Jetpack Compose application created in this way does not need to be configured manually, AS has been automatically added for us

How do existing projects support Jetpack Compose

If you want to use Jetpack Compose in an existing project, you need to add the following configuration and dependencies

1. Configuration Kotlin

Make sure you are using Kotlin 1.4.30 in your project and add the plugin to your app’s build.gradle

plugins {
  id 'org.jetbrains.kotlin.android' version '1.4.30'
}
Copy the code

2. Configuration Gradle

The lowest API version for your app needs to be >=21 and enable Jetpack Compose in your app’s build.gradle, as shown below

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

    composeOptions {
        kotlinCompilerExtensionVersion '1.0.0 - beta01'}}Copy the code

3. Add Jetpack Compose dependency

You need to add the Jetpack Compose dependency to your app’s build.gradle

dependencies {
    implementation 'androidx.com pose. The UI: UI: 1.0.0 - beta01'
    // Tooling support (Previews, etc.)
    implementation 'androidx.com pose. The UI: UI - tooling: 1.0.0 - beta01'
    // Foundation (Border, Background, Box, Image, Scroll, shapes, animations, etc.)
    implementation 'androidx.com pose. Foundation, foundation: 1.0.0 - beta01'
    // Material Design
    implementation 'androidx.com pose. Material: material: 1.0.0 - beta01'
    // Material design icons
    implementation 'androidx.com pose. Material: material - the ICONS - the core: 1.0.0 - beta01'
    implementation 'androidx.com pose. Material: material - the ICONS - extended: 1.0.0 - beta01'
    // Integration with activities
    implementation 'androidx. Activity: activity - compose: 1.3.0 - alpha03'
    // Integration with ViewModels
    implementation 'androidx. Lifecycle: lifecycle - viewmodel - compose: 1.0.0 - alpha02'
    // Integration with observables
    implementation 'androidx.com pose. The runtime: the runtime - livedata: 1.0.0 - beta01'
    implementation 'androidx.com pose. The runtime: the runtime - rxjava2:1.0.0 - beta01'

    // UI Tests
    androidTestImplementation 'androidx.com pose. The UI: UI - test - junit 4:1.0.0 - beta01'
}
Copy the code

4. An introduction to some of Compose’s tools

As we know, traditional Android development is done by writing XML layout files. And preview our UI layout via AS. Now Compose has its own way to preview the layout.

1.@Preview Preview function

1. Preview composable items

Composable items are defined by functions and annotated with @composable. For example, here we define the combination item tabItem. TabItem is a vertical layout with the icon icon above and the text text below.

@Composable
fun tabItem(a){
    Column{
     Icon(vectorResource(id = R.drawable.ic_launcher_background))
     Text(text = "Ha ha ha.")}}Copy the code

If we need to Preview the Composable, we need to create another Composable annotated with @composable and @Preview and issue the Composable that you originally created:

@Preview
@Composable
fun tabItemPreview(a) {
    tabItem()
}
Copy the code

1 Open the right panel to display preview: select Split

2 There is a run icon to the left of the tabItemPreview () function. Click on the run icon. You can preview our composables in the Split panel

1.2 Interactive Mode (Directly interact in the Preview panel)

With interactive mode, you can interact with preview objects in a manner similar to what you would do on a device. In this mode, you can click on elements in the preview object and enter user input; Preview objects can even play animations. Using this mode, you can quickly test different states and gestures for composable items, such as checking or clearing check boxes. \

Preview Interactive mode runs directly in Android Studio without running emulators, so there are some limitations:

Unable to access the network

Unable to access files

Some Context apis may not be fully available, as shown in the following example

We can do this by clicking the Start Interactive Model icon on the preview image in the panel. You can now do some interaction with the preview. When you Stop, click Stop Interactive Model. The icon is shown below.

1.3 Deploying preview Objects

You can deploy Preview objects with specific @Preview annotations to emulators or physical devices. In the Preview panel, select a Preview object and click the Deploy Preview button. The ICONS are shown belowOnce clicked, you can preview the preview object on your phone or emulator

1.4 Code navigation and view of composable outline

You can hover over the preview object to see an outline of the composable items it contains. Clicking the composable item outline triggers your editor view to navigate to its definition.

1.5 Copy @preview for rendering

Each preview object rendered can be copied as an image by right-clicking it.

2.@Preview Preview configuration

@Preview uses additional parameters to change the Preview rendering configuration. You can set these parameters manually in your code or change them by previewing the sideline icon:Let’s take a look at the source code of the preview class

@MustBeDocumented
@Retention(AnnotationRetention.SOURCE)
@Target( AnnotationTarget.FUNCTION )
@Repeatable
annotation class Preview(
    val name: String = "".// Set the name
    val group: String = "".@IntRange(from = 1) val apiLevel: Int = -1.// TODO(mount): Make this Dp when they are inline classes
    val widthDp: Int = -1.// Set the width
    // TODO(mount): Make this Dp when they are inline classes
    val heightDp: Int = -1.// Set the height
    val locale: String = "".// Set the language
    @ FloatRange (from = 0.01) val fontScale: Float = 1f.val showSystemUi: Boolean = false.// Displays the system UI
    val showBackground: Boolean = false.val backgroundColor: Long = 0.@UiMode val uiMode: Int = 0.@Device val device: String = Devices.DEFAULT
)
Copy the code
  • Name is the name of the set preview object. After setting, you can see the name in the panel
  • WidthDp is set width
  • HeightDp sets the height
  • Locale Setting language
  • FontScale User preference for font scaling factor (relative to base font) * density scaling.
  • ShowSystemUi sets the title bar (similar to a Toolbar) to display the system
  • ShowBackground Specifies whether to display the background
  • BackgroundColor backgroundColor
  • UiMode sets dark mode or light mode, etc

We can see a lot of inputs. These are parameters that we can configure. Here are a few examples

2.1 Configuring the Width and Height

For example, configure the width and height

@Preview(widthDp = 100,heightDp = 100)
@Composable
fun tabItemPreview(a){
    tabItem()
}
Copy the code
2.2 Setting Background

By default, your composable items are displayed on a transparent background. To add a background, add the showBackground and backgroundColor parameters. Note that backgroundColor is ARGB Long, not Color value:

@Preview(showBackground = true, backgroundColor = 0xFF00FF00)
@Composable
fun WithGreenBackground(a) {
    Text("Hello World")}Copy the code
2.3 Setting the Language

To test different user locales, add the locale parameter:

@Preview(locale = "fr-rFR")
@Composable
fun DifferentLocaleComposablePreview(a) {
    Text(text = stringResource(R.string.greetings))
}
Copy the code

3. Editor operation.

Android Studio also provides some features in the editor area that can make working with Jetpack Compose more productive.

3.1 Real-time Template

Android Studio has added the following real-time templates related to Compose that allow you to enter code snippets for quick insertion by typing the appropriate template abbreviation

3.2 Edge ICONS

The sidebar icon is the context action visible in the sidebar, next to the line number. Android Studio has introduced multiple Jetpack Compose dedicated sidebar ICONS to simplify the developer experience.

3.2.1 Preview selectors

You can change the @Preview parameter directly through the sidebar icon

3.2.2 Deployment Preview Object icon

You can deploy @Preview directly to emulators or physical devices using the sideline icon:

3.2.3 Color picker

Whether you define a color inside or outside a composable item, its preview object is displayed on the edge. You can click on the color and make changes through the color picker, as shown below:

3.2.4 Image resource selector

Whether you define a drawable object, vector, or image inside or outside a composable item, its preview object is displayed on the sidelines. You can click on it to make changes through the image resource picker, as shown below

Iterative code development

4.1 Apply Changes

Apply Changes lets you update your code and resources without having to redeploy your application to an emulator or physical device, but there are some limitations to this feature. Each time you add, modify, or remove composable items, you can update the application with a single click without having to redeploy

5. Layout inspector

The Layout Inspector allows you to check the Compose Layout of a running application on an emulator or physical device.

6. The animation

Android Studio allows you to check animations through interactive previews. If you describe the animation effect in the composable item preview, you can check the exact value of each animation value at a given time, and you can pause, loop, fast-forward, or slow down the animation to debug the animation during the animation transition:

@Preview
@Composable
fun PressedSurface(a) {
    val (pressed, onPress) = remember { mutableStateOf(false)}val transition = updateTransition(
        targetState = if (pressed) SurfaceState.Pressed else SurfaceState.Released
    )

    val width by transition.animateDp { state ->
        when (state) {
            SurfaceState.Released -> 20.dp
            SurfaceState.Pressed -> 50.dp
        }
    }
    val surfaceColor by transition.animateColor { state ->
        when (state) {
            SurfaceState.Released -> Color.Blue
            SurfaceState.Pressed -> Color.Red
        }
    }
    val selectedAlpha by transition.animateFloat { state ->
        when (state) {
            SurfaceState.Released -> 0.5 f
            SurfaceState.Pressed -> 1f
        }
    }

    Surface(
        color = surfaceColor.copy(alpha = selectedAlpha),
        modifier = Modifier
            .toggleable(value = pressed, onValueChange = onPress)
            .size(height = 200.dp, width = width)
    ){}
}
Copy the code

To enable the animation inspector, click this button: