1. Introduction

Jetpack Compose is a new library that was announced at Google I /O 2019. The Compose library is a responsive programming approach to View building, which allows for faster development with less code, more intuitive code, and more powerful functionality. To be fair, the View/Layout model is too familiar to Android engineers, so I’m worried about the steep learning curve for Jetpack Compose.

Because Jetpack Compose has a lot of content, I’ll break it down into several articles. It covers the use of common UI components, the combination of Flow and Compose, and how to build MVVM applications. In addition, the Compose API has not been fully determined, if there are API changes, I will also revise the article, so please rest assured.

The first shell will cover how to create the Compose application and the basic annotation, the use of the Compose method. All right, let’s cut to the chase!

2. The tutorial

2.1 Create new projects or import libraries

Jetpack Compose has been supported since Android Studio 4.2, so you need to create a new project or add an import library via 4.2(now Canary). Creating a new project is described here.

As shown in the figure above, you need to select the Empty Compose Activity when creating a new project.

The build.gradle file in the module will add the following library dependencies.

dependencies {
    ...
    implementation 'androidx.ui:ui-layout:"${compose_version}"'
    implementation 'androidx.ui:ui-material:"${compose_version}"'
    implementation 'androidx.ui:ui-tooling:"${compose_version}"'
    ...
}
Copy the code

Also add the following Settings to the build.gradle file of the module.

android { ... buildFeatures { compose true } composeOptions { kotlinCompilerExtensionVersion "${compose_version}" KotlinCompilerVersion "1.3.70 - dev - withExperimentalGoogleExtensions - 20200424"}}Copy the code

2.2 the UI related

2.2.1 @ Compose

All methods for building a View must be annotated with @compose. And @compose is similar to the method Suspend of the coroutine. Methods annotated by @compose can only be called from methods also annotated by @comopse.

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

2.2.2 @ the Preview

The @Preview annotation allows you to verify the layout without running the App.

The more common arguments in the @preview annotations are as follows:

  1. name: String: Gives the Preview a name that will appear in the layout Preview.
  2. showBackground: Boolean: Indicates whether to display the background. True indicates that the background is displayed.
  3. backgroundColor: Long: Sets the background color.
  4. showDecoration: Boolean: Indicates whether to display the Statusbar and Toolbar.
  5. group: String: Sets the group name for the Preview, which can be displayed in groups in the UI.
  6. fontScale: FloatThe font can be enlarged in the preview. The range is 0.01.
  7. widthDp: Int: The maximum render width in Compose in dp.
  8. heightDp: Int: The maximum height rendered in Compose in dp.

The above parameters are optional, and the parameters such as background Settings are not set for the actual App, but for the background in Preview, in order to see the layout more easily.

@Preview(showBackground = true, name = "Home UI", showDecoration = true)
@Composable
fun DefaultPreview() {
 MyApplicationTheme {
 Greeting("Android")
 }
} 
Copy the code

There are Code, Split, and Design options in the upper right corner of the IDE. Code only, both code and layout, and layout only. When you change ui-related code, a horizontal bar notification is displayed as shown below, and you can hit Build&Refresh to update the UI that displays the changed code.

2.2.3 setContent

So setContent does the same thing as setContentView in zaiLayout/View. The setContent method is also a method that has the @compose annotation. So, in setContent, write the @compopse method on the UI to be displayed in the Activity.

override fun onCreate(savedInstanceState: Bundle?) {
 super.onCreate(savedInstanceState)
 setContent {
 JetpackComposeDemoTheme {
 Greeting("Android")
 }
 }
 } 
Copy the code

2.2.4 * Theme

A @compose method with the project name +Theme is automatically created when a new Compose project is created. We can set the theme color by changing the color. The generated code for the Theme method is shown below.

private val DarkColorPalette = darkColorPalette(
 primary = purple200,
 primaryVariant = purple700,
 secondary = teal200
)
 private val LightColorPalette = lightColorPalette(
 primary = purple500,
 primaryVariant = purple700,
 secondary = teal200
 /* Other default colors to override
 background = Color.White,
 surface = Color.White,
 onPrimary = Color.White,
 onSecondary = Color.Black,
 onBackground = Color.Black,
 onSurface = Color.Black,
 */
)
 @Composable
fun JetpackComposeDemoTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable() () -> Unit) {
 val colors = if (darkTheme) {
 DarkColorPalette
 } else {
 LightColorPalette
 }
 MaterialTheme(
 colors = colors,
 typography = typography,
 shapes = shapes,
 content = content
 )
} 
Copy the code

The Theme method has color Settings for normal and Dark themes, as well as Settings for MeterialTheme.

Here’s how to use the Theme method.

setContent {
 JetpackComposeDemoTheme {
 Greeting("Android")
 }
 } 
Copy the code

All UI methods in JetpackComposeDemoTheme will apply the colors specified in the theme above.

2.2.4 Modifier

Modifier is a class that each Compose UI component must use. It’s the class that’s used to set the placement of the UI, the padding, etc. On the Modifier related Settings are too many, only here will be often used.

  • paddingSet the padding of each UI. There are four ways to overload a padding.
Padding-bottom (10. Dp, 11. Dp, 12. 13. / / dp) is set up and down around value respectively Modifier. The padding (10. Dp, 11. Dp) / / is set up and down and left and right sides respectively Modifier. The padding (InnerPadding (10. Dp, 11. Dp, 12. Dp, 13. Dp))// set the upper, lower, and left values respectivelyCopy the code
  • plusYou can add another Modifier to the current Modifier.
Plus (otherModifier) // Add the otherModifier information to the existing ModifierCopy the code
  • fillMaxHeight.fillMaxWidth.fillMaxSizeSimilar to thematch_parentFills the entire parent layout.
Modifier.fillMaxHeight() // Fill the entire heightCopy the code
  • width.heigh.sizeSet the width and height of the Content.
Height (3. Dp) // Set the Height Modifier. Size (4. Dp, 5. Dp) // Set the height and width copy codeCopy the code
  • widthIn.heightIn.sizeInSets the maximum and minimum width and height of the Content.
Heightener. SizeIn (4. Dp, 5. Dp, 6. Dp, heightener. 7. Dp) // Set the maximum and minimum width and heightCopy the code
  • gravityColumnThe position of the element in.
Modifier. Gravity (Alignment. CenterHorizontally) / / horizontal center Modifier. The gravity (Alignment. Start) / / transverse in the left Gravity (Alignment.End) // Horizontal Alignment to the rightCopy the code
  • rtl.ltrStart laying out the direction of the UI.
RTL // Right-to-left modifier. LTR // Left-to-right copy the code '</pre> Modifier methods all return chained calls to instances of Modifier, so just make successive calls to the desired method. <pre>`@Composable fun Greeting(name: String) { Text(text = "Hello $name!" , modifier = Modifier.padding(20.dp).fillMaxSize()) }Copy the code

2.2.5 Column and Row

Column and Row are, as their names suggest, vertical and horizontal viewgroups in a View/Layout architecture. There are four parameters you need to pass in.

  • Modifier with the above method into the Modifier has been set up according to the demand.

  • Horizontal, arrangement. Vertical, Row arrangement. Horizontal, Column arrangement. Vertical These values determine how the internal UI components are laid out. The values that can be passed in are Center, Start, End, spaceinstituted, SpaceBetween, SpaceAround. Finally, a spaceinstituted, SpaceAround.

Spaceinstituted: The gap between elements is evenly proportioned.

SpaceBetween: There is no gap before the first element and after the last element. All gaps are placed between elements in equal proportions.

SpaceAround: Put half of the gap in the whole into the front of the first element and after the last element equally, and put the remaining half in equal proportion between each element.

  • Horizontal needs to be passed to Row in Alignment.Vertical, Column in Alignment.Horizontal. The usage method is the same as that of the gravity parameter passed in the Modifier, which will be skipped here.

  • @composable ColumnScope.() -> Unit requires the UI method marked @compose to be passed in. But here we’ll have the lamda function to do it.

The overall code is as follows.

Column { Row(modifier = Modifier.ltr.fillMaxWidth(),horizontalArrangement = Arrangement.SpaceAround, verticalGravity = Alignment.Top) { // .. . }Copy the code

3. The other

Compose is objectively difficult to learn because it’s so new and big. It’s also true that Compose is a completely new framework that many people find difficult to learn.

So what to do? What if I can’t learn?

For those of you who don’t have enough learning materials, I just picked up the “Jetpack Compose” guide, which is composed for you to get started with. The tutorial is easy to understand and contains many examples, including both basic knowledge and advanced skills. Learn about Jetpack Compose and add it to your collection.

Chapter 1: Jetpack Compose

1. Why do we need a new UI tool?

2. Focus on Jetpack Compose

  • To accelerate the development
  • Powerful UI tools
  • Intuitive Kotlin API

3. API design

4. The Compose API principles

  • Everything is a function
  • Top level function
  • Composition over Inheritance
  • Trust a single source

5. Learn more about Compose

  • Core
  • Foundation
  • Material

6. Socket API

Chapter 2 Jetpack Compose builds the Android UI

1. Android Jetpack Compose is a beginner’s guide

  • Jetpack Compose environment ready and Hello World
  • layout
  • Design using Material Design
  • Real-time preview of the Compose layout

2. Further explanation Jetpack Compose | optimized UI building

  • Compose solves the problem
  • Composable function profile
  • Declarative UI
  • Composition vs inheritance
  • encapsulation
  • restructuring

3. In-depth explanation Jetpack Compose | implementation principle

  • What does @composable note mean?
  • Execution mode
  • Positional Memoization
  • Storage parameters
  • restructuring

Chapter 3 Jetpack Compose Project Practice (with Demo)

1. Jetpack Compose app 1

  • Preparation before starting
  • Create a DEMO
  • Problems encountered

Jetpack Compose app 2

3. Make a timer for Jetpack Compose

  • The data structure
  • Countdown function
  • The state pattern
  • Compose layout
  • Draw a clock

4. Write a playable Android App with Jetpack Compose

  • The preparatory work
  • Introduction of depend on
  • The new Activity
  • Create a composer
  • PlayTheme
  • Draw the page
  • Bottom navigation bar
  • Manage state
  • Add a page

5. Write a weather app with Compose Android

  • The opening
  • Draw the page
  • Draw the background
  • Draw the content

6. Compose a quick “Movie App”

  • The finished product
  • Implementation scheme
  • In actual combat
  • insufficient

Friends in need just need to like support, and then [Get it for free here】