preface

I haven’t updated the original article for a long time. Due to changing my job, I had little time to write the article in the past two months. I was reviewing and preparing for the interview, and I got several good offers. Now new work dust settled, take advantage of these days of idle time, drag more articles up. At the end of last year’s review, I decided that Kotlin, Jetpack, and Compose would be my main focus for this year. The release of the beta version of Jetpack Compose in March, coupled with Google’s official four-week challenge game, has created a lot of buzz for Compose. I’ve always been a big fan of Jetpack Compose, and now is a good time to learn about it. So today I’m going to start the Jetpack Compose series.

What is Jetpack Compose?

Jetpack Compose is a new UI toolkit from Google designed to help developers build Native apps on the Android platform faster and easier. Jetpack Compose is a declarative UI framework that provides a modern declarative Kotlin API that replaces Android’s traditional XML layout to help developers build beautiful, responsive applications with less code.

The official description is not easy to understand. There is one word in it: declarative. So what is declarative?

To understand what declarative is, let’s first look at another concept: imperative. This is how we’ve been developing Android Native. Suppose we have a scenario where we want to display text on the interface. What is the difference between a declarative and an imperative implementation?

Imperative mode:

  • 1. First you need an XML file with a TextView inside
.<TextView
        android:id="@+id/my_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
Copy the code
  • 2, through thefindViewByIdGet the TextView control
TextView textView = findViewById<TextView>(R.id.my_text);
Copy the code
  • 3, throughsetText()Update the data and display it on the interface
textView.setText(content)
Copy the code

Declarative mode:

How do you do that in Compose’s declarative mode? It’s simple, one step at a time:

@Composable
fun ShowText(content: String){
    Text(text = content)
}
Copy the code

Why is the first imperative and the second declarative? This is mainly reflected in the interface update, in the imperative mode: When data is updated, Java code manually calls XML component reference to update the interface, that is, Java code commands XML interface update, which is the command mode. And declarative? It just describes the interface, and automatically updates the interface when the data state is updated, which is declarative.

Brief summary:

  • Imperative is the operation interface
  • Declarative is the description interface

In addition to Jetpack Compose, Flutter, react-Native, swift-UI are all declarative, which is also a trend now.

Jetpack Compose development environment ready

Android Studio has good support for Jetpack Compose. For a better experience, let’s download the latest Android Studio preview version of Canary. The latest version for the Arctic Fox (2020.3.1) Canary 14, download address is: developer.android.com/studio/prev…

After downloading, directly install, if the Mac version, download, decompress can be directly used. In general, it is recommended that you install two versions of Android Studio, one is a preview version, which is used to explore and try out new technologies and features, and one is a stable version, which is used for daily development. I am anyway.

With Android Studio ready, we can start creating the Jetpack Compose project.

First, click on Projects -> New Project to navigate to the Template selection screen. There is a New Empty Compose Activity template, so select this one. By default, it will help you configure the configuration and libraries for Jetpack Compose.

Click Next to configure the project name, registration, save path, etc.

Click Finish. The simplest Jetpack Compose Hello World app is now available.

This is the easiest way to create a new project because you only need to select the Jetpack Compose template and the rest is automatically configured for us. Jetpack Compose supports blending with existing projects. Just add support for Jetpack Compose and you can mix both. This is done by adding configuration to two build.gradle files:

In the root directory build.gralde:

Make sure Kotlin is version 1.4.30 or higher:

Classpath "org. Jetbrains. Kotlin: kotlin - gradle - plugin: 1.4.32"Copy the code

Gradle configuration in app directory:

You need to configure the following items:

android {

    // 1. Ensure that the minimum SDK version is 21 or higher
    defaultConfig {
        ...
        minSdkVersion 21
    }

   
    buildFeatures {
        // 2. Enable Jetpack Compose
        compose true}...// set the Java and Kotlin compilers to Java8compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions  { jvmTarget ="1.8"
    }

    // Add the extended version of the Kotlin compiler
    composeOptions {
        kotlinCompilerExtensionVersion '1.0.0 - beta01'}}Copy the code

Add some dependency libraries for Jetpack Compose development:

Dependencies {implementation 'androidx.com pose. The UI: UI: 1.0.0 - beta01' / / tools support library implementation 'Androidx.com Tolling: tolling: tolling: tolling' // Compose base library, Contains various compose components (Border, Background, Box, Image, Scroll, Shapes, animations, Etc.) implementation 'androidx.com pose. Foundation, foundation: 1.0.0 - beta01' / / Material Design repository implementation 'androidx.com pose. Material: material: 1.0.0 - beta01' / / material design icon library 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' / / activities to integrate library implementation 'androidx. Activity: activity - compose: 1.3.0 - alpha03' / / ViewModels integrated library implementation 'androidx. Lifecycle: lifecycle - viewmodel - compose: 1.0.0 - alpha02'/library/observables integration 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' androidTestImplementation / / UI test 'androidx.com pose. The UI: UI - test - junit 4:1.0.0 - beta01'}Copy the code

These are all possible libraries that can be added selectively, with the integration libraries matching the corresponding libraries in Jetpack, such as Activitys, ViewModel, etc.

That adds support for Jetpack Compose.

Compose code and tool introduction

Let’s start with the code:

class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Surface(color = MaterialTheme.colors.background) { Greeting("Android")  } } } } @Composable fun Greeting(name: String) { Text(text = "Hello $name!" ) } @Preview(showBackground = true) @Composable fun DefaultPreview() { Greeting("Android") }Copy the code

The Composable Kotlin function with @composable is the Compose component. The Composable Kotlin function is composed, and the Composable Kotlin function is composed. The Composable Kotlin function is composed. So the above Greeting and DefaultPreview are both a Compose component.

Preview tool

In Compose, how do you preview the Compose interface (component)? Just add the @Preview annotation to the Compose component to Preview, and the Preview area will appear on the right side of the panel:

Multiple previews can be added to the preview panel. Multiple previews of the same file will be displayed in the preview panel. For example, if we add another one:

@composable fun OtherPreview() @composable fun OtherPreview() {Composable fun OtherPreview() @composable fun OtherPreview() {Composable fun (); I'm Sigo!" )}Copy the code

Two previews appear in the preview panel:

In addition, the Preview annotations add configuration parameters, such as the size of the Preview, color, whether to show the background, and so on. As follows:

@Preview( showBackground = true, widthDp = 200, heightDp = 420, backgroundColor = 0x1e7d73 )
    @Composable
    fun DefaultPreview(a) {
        Greeting("Android")}}Copy the code

The preview looks like this:

There are a few other parameters you can configure for @preview, such as group Preview, changing the name of the Preview, and so on.

@Repeatable
annotation class Preview(
   val name: String = "".val group: String = "".@IntRange(from = 1) val apiLevel: Int = -1.// TODO(mount): Make this Dp when they are inline classes
   val widthDp: Int = -1.// TODO(mount): Make this Dp when they are inline classes
   val heightDp: Int = -1.val locale: String = "".@ FloatRange (from = 0.01) val fontScale: Float = 1f.val showSystemUi: Boolean = false.val showBackground: Boolean = false.val backgroundColor: Long = 0.@UiMode val uiMode: Int = 0.@Device val device: String = Devices.DEFAULT
)
Copy the code

Each preview view has two small buttons in the upper right corner:

On the left is the start interactive mode button, on the right is the release preview button.

** Interactive mode: ** After the interactive mode is enabled, you can operate like objects on the device, such as button clicking, list sliding, animation execution, input box input, etc.

For example, add a button, an input field, and a switch button:

Composable fun DefaultPreview() @composable fun DefaultPreview() {var text by remember {mutableStateOf(" Composable ")} var IsChecked by remember {mutableStateOf(false)} Column {Button(onClick = {}) {Text(" click ")} TextField(value = text, onValueChange = { text = it }, label = { Text("Label") } ) Switch( checked = isChecked, onCheckedChange = { isChecked = it } ) } }Copy the code

Preview effect:

Interactive mode effects:

Try it, in interactive mode, it seems that the input box can not be typed and clear, I don’t know whether it is a bug or not.

Release preview:

Release preview allows you to publish a build to a device to see what it looks like. Note that only the currently previewed components are published, not the entire interface.

conclusion

That’s the end of this article, which covers the integration of the Jetpack Compose development environment and the use of some tools. Now you’re ready to start Jetpack Compose! The next article will start with the Compose component Text! Stay tuned!

I am the west elder brother, welcome to pay attention to my public number: “technology is the most TOP”, dry goods article first time send read!