Make writing a habit together! This is the second day of my participation in the “Gold Digging Day New Plan · April More Text Challenge” click to see the details of the activity.

1. The introduction of Compose

It’s been nearly two years since Google announced Compose at ITS I/O conference in May 2019, the first Alpha release in September 2020, and the first Bate release in February 2021.

For those of you familiar with Flutter and SwiftUI, Jetpack Compose is a UI toolkit that is written in a very similar way. Since I have done Flutter development before, I feel strangely familiar with the Jetpack Compose library.

Jetpack Compose is a new toolkit for building native Android interfaces. It simplifies and speeds up interface development on Android, using less code, powerful tools, and an intuitive Kotlin API to make apps live and exciting quickly.


  • Less code: You can do more with less code and avoid bugs, making your code concise and easy to maintain
  • Intuitive: Just describe the interface, and Compose takes care of the rest. When the application status changes, the interface is automatically updated
  • Accelerated development: compatible with all existing code, easy to use anytime, anywhere. Fast iteration with live preview and full Android Studio support
  • Powerful: Direct access to Android platform API, built-in support for Material Design, dark theme, animation, etc., let you create beautiful applications
  • Wait…

2. Set up the development environment

1. To do a good job, he must sharpen his tools.

For Compose, you need to download the Android Studio version 4.3 or above. For Compose, you should download the latest version from the official website. The latest version is Android-Studio-2021.1.1.22. You can click on the official website link above to download the latest version.

Send you can download AS historical versions of the links below: Android Studio download archives | | Android Developers Android Developers

After downloading, you can install it

2. Create the Compose project

1. New Project Select Empty Compose Activity

2. Click Next and enter project configuration information

The Compose project requires a minimum API version of 21, which is 23 (Android 6.0). Click Finish and the creation is complete

> > < span style = “color: # 0000ff; color: # 0000ff; color: # 0000ff;

  • Color.kt: a class for storing colors, similar to the color.xml class before
  • Shape.kt: a class that holds resources such as shapes, similar to shapes in the drawable resources folder
  • Kt: a class for storing styles, similar to style.xml/theme.xml
  • Type.kt: the class that holds the style

Looking at the RES section, the obvious difference is that there is no layout folder, because Compose is a completely declarative component-based approach, pure code writing, and no XML layout file writing

To use the Compose project, you need to configure the required Settings and dependencies for the project. The first step is to configure the Kotlin development environment, which Compose requires Kotlin version 1.4.30 or higher. We need to add some code to the project-level build.gradle file. The version we are using here is 1.5.21

plugins { ... Id 'org. Jetbrains. Kotlin. Android' version '1.5.21 apply false}Copy the code

Add dependencies to build.gradle file in app Module:

plugins { ... id '' } android { ... compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions {jvmTarget = '1.8'} / / set to open compose buildFeatures composeOptions {compose true} {kotlinCompilerExtensionVersion Compose_version} packagingOptions {resources {excludes += '/ meta-INF /{AL2.0,LGPL2.1}'}}} dependencies { Implementation 'Androidx. core:core-ktx:1.7.0' implementation "androidx.compose. UI: UI :$compose_version Implement " pose. UI: UI-tolling :$compose_version" implementation (tolling :$compose_version "$compose_version" // Material Design implementation " pose. Material: material: $compose_version" / / material Design icon implementation " pose. Material: material - the ICONS - the core: 1.1.1" implementation " pose. Material: material - the ICONS - extended: 1.1.1" / / combined with Activity implementation 'androidx. Activity: activity - compose: 1.3.1' / / with the viewmodel combined implementation "Androidx. Lifecycle: lifecycle - viewmodel - compose: against 2.4.1" / / combined with livedata implementation " pose. The runtime: the runtime - livedata: 1.1.1" / / combined with RxJava3 implementation " pose. The runtime: the runtime - rxjava3:1.1.1" / / combined with RxJava2 use / / implementation " pose. The runtime: the runtime - rxjava2:1.1.1" implementation "androidx.compose.ui:ui-tooling-preview:$compose_version" implementation 'androidx. Lifecycle: lifecycle - runtime - KTX: 2.3.1' testImplementation junit: junit: 4.13.2 androidTestImplementation 'androidx. Test. Ext: junit: 1.1.3' androidTestImplementation 'androidx. Test. Espresso: espresso - core: 3.4.0' androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version" }Copy the code

The dependencies listed above do not have to be added all together and can be optionally added based on the needs of the project. There are also many libraries that depend on Compose, which are not listed here.

3. Add Compose to an existing project

If you want to use Compose in an existing project, you need to configure the Settings and dependencies required for the project. For details, see Step 2

3. Analyze your new Compose project

1. Run the project

Let’s take a look at the MainActivity code first:

class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MyComposeDemoTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background ) { Greeting("Android") } } } } } @Composable fun Greeting(name: String) { Text(text = "Hello $name!" ) } @Preview(showBackground = true) @Composable fun DefaultPreview() { MyComposeDemoTheme { Greeting("Android") } }Copy the code

The above code is automatically generated by directly creating the Compose project. As you can see, the Compose entry is still an Activity, but the difference is that the setContentView method in the onCreate method has been replaced with setContent. See what we don’t know, click on it to see the source code:

public fun ComponentActivity.setContent( parent: CompositionContext? = null, content: @Composable () -> Unit ) { val existingComposeView = window.decorView .findViewById<ViewGroup>( .getChildAt(0) as? ComposeView if (existingComposeView ! = null) with(existingComposeView) { setParentCompositionContext(parent) setContent(content) } else ComposeView(this).apply { // Set content and parent **before** setContentView // to have ComposeView create the composition on attach setParentCompositionContext(parent) setContent(content) // Set the view tree owners before setting  the content view so that the inflation process // and attach listeners will see them already present setOwners() setContentView(this, DefaultActivityContentLayoutParams) } }Copy the code

It turns out that this is an extension of ComponentActivity, and MainActivity also inherits from ComponentActivity. Look at the source code, through the setContent method can set the layout. In the MainActivity code, setContent is wrapped with MyComposeDemoTheme, which is the theme defined by Compose itself. The MyComposeDemoTheme wraps the Surface and specifies the background color of the page. The Greeting wraps the Surface and is the control that displays on the page. If we look at the Greeting method, we see that it has a Composable annotation @composable. We call this function Composable because this is the control that can be used in Compose. Note that using the Compose control:

  • This function must be annotated with @composable. This annotation tells the Compose compiler that this function is intended to convert data into an interface
  • Composable functions can take arguments
  • Composable functions have no return value
  • Composable functions have no side effects when describing interfaces

2. Preview

In the past, we were able to see a preview of our Android interface in real time when we were writing the XML layout. Now we can see a preview of the interface in real time when we are using Compose. The answer is yes. But how do we look at it? Here we need a new annotation: @Preview. Using this annotation and setting some parameters, we can see what the interface looks like in real time. If the preview effect is not updated in time after modifying the code, we can click the button below to refresh

Perview has many arguments:

@repeatable annotation Class Preview(val name: String = "", String = "", @intrange (from = 1) val apiLevel: Int = -1, val widthDp: Int = -1, // width val heightDp: Int = -1, // height val locale: String = "",// @FloatRange(from = 0.01) val fontScale: Float = 1f, val showSystemUi: Boolean = false,// Whether to display device status and action bar val showBackground: Boolean = false,// whether to display background val backgroundColor: Long = 0, // set backgroundColor @uimode val UiMode: Int = 0,// UI mode, such as dark mode @device val Device: String = devices. DEFAULT// Device to be used in preview)Copy the code

You can set different parameters according to your own needs


This article is about what Compose is and how to build a development environment for it. How to create a new Compose project and import Compose into an existing project. It introduces the Compose project’s directory changes and the code structure of the home page, the two commonly used annotations, and some of the Preview annotations’ parameters.

Now, please join me in the ocean of Compose’s knowledge and let’s learn and grow together.

The last

If you have a different opinion, please leave a comment below. I am Mu Xiaofeng, a shandong native who loves learning and programming. (The content of this article is only for learning reference, if there is infringement, I am very sorry, please contact the author immediately to delete.)