当前位置:网站首页>Get started quickly with jetpack compose Technology
Get started quickly with jetpack compose Technology
2022-06-25 09:52:00 【seevc】
One 、 What is? Compose?
Jetpack Compose yes Google New for Building native Android New toolkit for interface . It simplifies and speeds up Android Interface development on , Use less code 、 Powerful tools and intuitive Kotlin API, Quickly make the application vivid and exciting .
Two 、Compose The advantages of
- Less code
stay Android View System , To implement a function, you need to have XML and Kotlin/Java Two parts , And in the Compose There is no need to split the two parts in ,All the code is written in the same language and in the same file, Often complex functions can be solved with a few lines of code , therefore Compose The code is simple and easy to maintain .
Such as : Implement a list , Just a few lines of code
@Composable
fun Conversation(messages:List<Message>){
LazyColumn {
items(messages){ message->
MessageCard(message)
}
}
}
intuitive
Compose Use declarative API, That means just describing the interface ,Compose Will be responsible for completing the rest of the work , When the application state changes , The interface will refresh automatically .Accelerate application development
Compose Compatible with all existing codes , Easy to start using anytime, anywhere . With the help of comprehensive Android Studio Support and real-time preview function , Can iterate faster .Powerful
By right Android platform API Direct access and for Material Design、 Dark theme 、 Built in support for animation, etc , Create beautiful applications .
3、 ... and 、 Development environment preparation
IDE edition :Android Studio Arctic Fox
Language :Kotlin
Create support Jetpack Compose New applications for
open Android Studio, Execute sequentially File > New > New Project, In the pop-up New Project Select from the popover Empty Compose Activity, And then click Next, Set the corresponding Name、PackageName、 And storage location , Just click 【Finish】 Can finish Compose Engineering creation .
notes :1. Support only Kotlin.2. After the project is created, it will be automatically imported Compose Related basic libraries , If you need other toolkits, you can find them in Build.gradle To configure .
Four 、Compose Composable functions and previews
new Compose After the project is created , In the experience Compose Before development, let's learn about two key annotations .
* Composable function
Jetpack Compose Is built around composable functions . These functions allow you to define the application's interface programmatically , Just describe the appearance of the application interface and provide data dependencies , You don't have to pay attention to the construction process of the interface ( Initialization element , Attach it to the parent, etc ). To create composable functions , Just put the @Composable Just add the annotation to the function name .
@Composable
fun MessageCard(name: String) {
Text(text = "Hello $name!")
}
* Preview function
Android Studio Allow in IDE Preview composable functions in , No need to install the application on the device . Key notes used @Preview
@Preview
@Composable
fun DefaultPreview() {
MessageCard("Android")
}

5、 ... and 、 Layout
Interface elements adopt multi-level layout , Element contains other elements .Compose Call other composable functions through a composable function to build the interface .
- To add text
Use composable functionsTextAdd a text
@Composable
fun MessageCard(msg: Message) {
Text(text = msg.author)
}
- Use Column and Row
For multiple elements , How to lay it out ? At this point, we need to use Column and Row Function .ColumnThe function allows elements to be arranged vertically .RowFunction to arrange elements horizontally .
@Composable
fun MessageCard(message:Message) {
// That's ok
Row {
// Add a picture element
Image(
// Fill in the content
painter = painterResource(id = R.mipmap.ic_girl),
contentDescription = "logo",
)
// Column
Column{
Text(text = message.author)
Text(text = message.body)
}
}
}

- Add picture elements
The composable function used to add picture elements is :Image, See the example above . - Use modifiers to configure the layout
stay Compose The element in provides modifiers , By setting themodifier, You can change the size of an element 、 Layout 、 appearance 、 Interaction .
In the following example , to Image Add modifier
// Add a picture
Image(
// Fill in the content
painter = painterResource(id = R.mipmap.ic_girl),
contentDescription = "logo",
// Size and shape
modifier= Modifier
.padding(top = 2.dp)
.size(40.dp) // Image size
.clip(CircleShape) // Cut the shape
)

6、 ... and 、 Use Material Design
Compose Many of the interface elements of support Material Design.
The default theme will be generated in the created project , Support customization MaterialTheme.
- Set up a Material The theme style
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { // Set the theme JetpackDemoTheme { ...... } } } - Use theme colors
For example, add a circular border to the picture :// Add a picture Image( // Fill in the content painter = painterResource(id = R.mipmap.ic_girl), contentDescription = "logo", // Size and shape modifier= Modifier .padding(top = 2.dp) .size(40.dp) // Image size .clip(CircleShape) // shape .border(1.5.dp, MaterialTheme.colors.secondary, CircleShape)// Border style )
- Typesetting
MaterialTheme Provided in Material Typography , Just add it to Text Can be combined items .Text( text = message.author, color = MaterialTheme.colors.secondaryVariant, // add to MaterialTheme Typesetting style = MaterialTheme.typography.subtitle2 ) - Set border shape
// Set a border Surface(shape = MaterialTheme.shapes.medium, elevation = 2.dp, color = surfaceColor, modifier = Modifier.animateContentSize().padding(1.dp).clickable { isExpanded = !isExpanded } ){ Text(text = msg.body) }
- Enable dark themes
Development process , Preview supports enabling dark themes ( Night mode ),Jetpack Compose It can handle dark themes by default . Use Material Color 、 Text and background , The system will automatically adapt to the dark background .
The activation mode is as follows :@Preview(name = "Light Mode")// Day mode @Preview(showBackground = true,uiMode = Configuration.UI_MODE_NIGHT_YES,name = "Dark Mode")// Night mode @Composable fun DefaultPreview() { JetpackDemoTheme { MessageCard(Message("Android","Jetpack Compose")) } }

7、 ... and 、 Lists and animations
Lists and animations are very common in practical applications , Here is a simple way to learn how to use Compose Easily create lists and add animation effects .
Create a message list
Compose For usLazyColumnandLazyRowComposable function , Corresponding to vertical list and horizontal list respectively .@Composable fun Conversation(messages:List<Message>){ // List of vertical directions LazyColumn { items(messages){ message-> MessageCard(message) } } } // Define data classes data class Message(val author: String, val body: String)Static list diagram :

Show animation effects when expanding messages
First of all, will Text Set the number of rows of to one row , When clicked, expand all .
Use composable functions firstrememberRecord the expanded status of no rows , Save inmutableStateOfin , After this value is updated , The system will automatically and intelligently redraw the elements that use this state , This process is also calledrestructuring.@Composable fun MessageCard(message:Message) { ... var isExpanded by remember { mutableStateOf(false) } ... }You can now change this by clicking on the message
isExpandedA variable's value , Then modify the background and ICBC effect of the message according to this value .@Composable fun MessageCard(message:Message) { ... val surfaceColor: Color by animateColorAsState( if (isExpanded) MaterialTheme.colors.primary else MaterialTheme.colors.surface, ) Column{ ... // Set a border Surface(shape = MaterialTheme.shapes.medium, elevation = 2.dp, color = surfaceColor, modifier = Modifier.animateContentSize() .padding(1.dp) //1. Add a clickable event .clickable { isExpanded = !isExpanded } ){ Text( text = message.body, modifier = Modifier.padding(all = 4.dp), //2. Set the number of rows when expanding maxLines=if (isExpanded) Int.MAX_VALUE else 1, // add to MaterialTheme Typesetting style = MaterialTheme.typography.body2 ) } ... } ... }The last one with unfold and retract animation gif design sketch

The last attached
github Source code address
gitee - Sample source code
边栏推荐
- Voiceprint Technology (V): voiceprint segmentation and clustering technology
- [zufe expense reimbursement] zhecai invoice reimbursement specification (taking Xinmiao reimbursement as an example), which can be passed in one trip at most
- pmp考试题型需要注意哪些?
- 独步武林,架构选型手册(包含 PDF)
- C语言刷题随记 —— 猴子吃桃
- Pytorch_Geometric(PyG)使用DataLoader报错RuntimeError: Sizes of tensors must match except in dimension 0.
- Work of the 15th week
- What should be paid attention to in PMP examination?
- Set the location permission in the shutter to "always allow"
- Is it safe to open an account online? Who can I ask?
猜你喜欢

Learning notes of rxjs takeuntil operator

Data-driven anomaly detection and early warning of item C in the May 1st mathematical modeling competition in 2021

2022 postgraduate entrance examination experience post -- Alibaba Business School of Hangzhou Normal University -- management science and Engineering (including the recommendation of books and course

How to "transform" small and micro businesses (I)?

Rxjs TakeUntil 操作符的学习笔记

Notes on writing questions in C language -- monkeys eat peaches

Solution to the problem of repeated startup of esp8266

Summarize two methods of configuring pytorch GPU environment
![[2020 cloud development + source code] 30 minutes to create and launch wechat applet practical project | zero cost | cloud database | cloud function](/img/89/39851fee714be872a599ad4ddd4852.jpg)
[2020 cloud development + source code] 30 minutes to create and launch wechat applet practical project | zero cost | cloud database | cloud function

Study on correlation of pumpkin price and design of price prediction model based on BP neural network
随机推荐
Oracle function trigger
SQL高级
C语言刷题随记 —— 猴子吃桃
Download the arm64 package of Debian on X86 computer
【mysql学习笔记20】mysql体系结构
8. Intelligent transportation project (1)
瑞萨RA系列-开发环境搭建
Creating a binary tree (binary linked list) from a generalized table
manhattan_slam环境配置
oracle 函数 触发器
【mysql学习笔记22】索引
手机办理长城证券开户靠谱安全吗?
Is it safe to open an account online? Who can I ask?
如何自制一个安装程序,将程序打包生成安装程序的办法
Data-driven anomaly detection and early warning of 21 May Day C
vscode试图过程写入管道不存在
How to make a self-made installer and package the program to generate an installer
Tiktok brand goes to sea: both exposure and transformation are required. What are the skills of information flow advertising?
[shared farm] smart agriculture applet, customized development and secondary development of Kaiyuan source code, which is more appropriate?
Force buckle -104 Maximum depth of binary tree