当前位置:网站首页>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
边栏推荐
- Oracle function trigger
- Lvs-dr mode single network segment case
- Mysql 源码阅读(二)登录连接调试
- Wearable devices may reveal personal privacy
- Use evo
- 2台三菱PLC走BCNetTCP协议,能否实现网口无线通讯?
- 2021mathorcupc topic optimal design of heat dissipation for submarine data center
- Rxjs TakeUntil 操作符的学习笔记
- Ruiji takeout project (II)
- How to "transform" small and micro businesses (II)?
猜你喜欢

vscode试图过程写入管道不存在

Reza RA series - development environment construction

Question B of the East China Cup: how to establish a population immune barrier against novel coronavirus?

Use Navicat to compare data differences and structure differences of multi environment databases, and automatic DML and DDL scripts
![[MySQL learning notes 22] index](/img/08/db7b765f7ddaa5706e3f7d00690d23.png)
[MySQL learning notes 22] index

【mysql学习笔记21】存储引擎

22 mathematical modeling contest 22 contest C

Rxjs TakeUntil 操作符的学习笔记

Register the jar package as a service to realize automatic startup after startup

Exception: gradle task assemblydebug failed with exit code 1
随机推荐
Where is safe for FTSE A50 to open an account
Fluent creates, reads and writes JSON files
2022 postgraduate entrance examination experience post -- Alibaba Business School of Hangzhou Normal University -- management science and Engineering (including the recommendation of books and course
Register the jar package as a service to realize automatic startup after startup
Wearable devices may reveal personal privacy
Is it safe to open an account with Great Wall Securities by mobile phone?
Processing picture class library
Swift recursively queries the array for the number closest to the specified value
Chitubox micromake l3+ slicing software configuration correspondence
Flutter dialog: cupertinoalertdialog
Reasons for Meiye to choose membership system
[buuctf.reverse] 121-125
CYCA 2022少儿形体礼仪初级师资班 深圳总部站圆满结束
8. Intelligent transportation project (1)
MySQL创建给出语句
manhattan_ Slam environment configuration
[design completion - opening report] zufeinfo 2018 software engineering major (including FAQ)
CyCa 2022 children's physical etiquette primary teacher class Shenzhen headquarters station successfully concluded
Mysql 源码阅读(二)登录连接调试
瑞吉外卖项目(二)