当前位置:网站首页>Jetpack compose layout (III) - custom layout
Jetpack compose layout (III) - custom layout
2022-06-25 09:52:00 【seevc】
In the first chapter 《Jetpack Compose Get started quickly 》 In this article, we briefly introduce Compose, So here we are going to learn Compose Layout . Because the layout involves a lot of content , Can write separately .
The layout mainly includes : Layout Basics 、Material Components and layout 、 Custom layout 、Compose Use in ConstraintLayout.
Custom layout Knowledge points involved :
Compose The process of layout
stay Compose in , Interface elements are represented by composable functions , This kind of function will emit part of the interface after being called , This part of the interface will then be added and displayed in the interface tree on the screen . Every interface element has a parent element , There may also be multiple child elements . Besides , Each element has a position in its parent element , Designated as (x, y) Location ; Also have a size , Designated as width and height.
The parent element defines the constraints of its child elements . The element needs to define dimensions within these constraints . Constraints can limit the minimum and maximum of elements width and height. If an element has child elements , It may measure each child element , To help determine its size . Once an element has determined and reported its own size , There is an opportunity to define how to place its child elements relative to itself .
The process of arranging each node in the interface tree is divided into three steps :1. Measure all sub items 2. Determine your own size 3. Place its children 
* Be careful :Compose Multiple measurements are not allowed on the interface . It means , Layout elements cannot measure any child elements multiple times in order to try different measurement configurations .
Extended layout modifier layout
Use layout Modifier to modify the measurement and layout of elements .Layout It's a lambda; Its parameters include elements that you can measure ( With measurable Form transfer ) And the incoming constraints of the composable item ( With constraints Form transfer ). A custom layout modifier might look like this :
fun Modifier.customLayoutModifier(...) =
this.layout { measurable, constraints ->
...
})
Let's say Text For example, the top inner margin of , If there is such a demand : Set the inner margin with reference to the baseline of the first line of text , As shown in the figure below :
Text location Y = Set height - Text height
The code is as follows :
/**
* 1. Custom layout modifiers - Change the distance between the text baseline and the top
*/
fun Modifier.firstBaselineToTop(firstBaselineToTop: Dp)=layout { measurable, constraints ->
// Measure first
val placeable = measurable.measure(constraints)
check(placeable[FirstBaseline] != AlignmentLine.Unspecified)
val firstBaseLine = placeable[FirstBaseline]
// Text location Y
val placeableY = firstBaselineToTop.roundToPx() - firstBaseLine
val height = placeable.height + placeableY
// Rearrange
layout(placeable.width,height){
placeable.placeRelative(0,placeableY)
}
}
The end result is the same as pading The effect is compared , Here's the picture :
Create a custom layout Layout
stay Android View If you want to customize the layout in the system , You have to inherit ViewGroup And realize the measurement and layout functions , And in the Compose It is much simpler to customize the layout in , Can be used directly Layout Items can be combined to achieve ,Layout Allow manual measurement and placement of sub items .Column and Row Is the Layout Built from .
Here, you should pay attention to the... In the custom modifier layout distinguish .
Let's take customizing a vertical layout as an example ( similar Column), The code is as follows :
/**
* 2. Customize Layout Implement vertical layout of components
*/
@Composable
fun MyBasicColumn(
modifier: Modifier = Modifier,
content:@Composable ()->Unit
){
// Step one :
// among measurables,constraints by Layout Of the last parameter lambda How to write it
Layout(content = content, modifier = modifier){ measurables,constraints ->
// Step two : By giving constraints to points constraints Measure the components
val placeables = measurables.map {
it.measure(constraints)
}
// Get the total height of all elements
val wrapHeight = placeables.sumOf {
it.height
}
// Step three : Layout , Set the allowable layout size
layout(constraints.maxWidth,wrapHeight){
var yPosition = 0
// Step four : Set the location of each component
placeables.forEach {placeable->
// Setup component x,y coordinate
placeable.placeRelative(x = 0,y=yPosition)
// Calculate the... Of the next component y coordinate
yPosition += placeable.height
}
}
}
}
It is worth noting that :Layout And layout The modifier is similar to , But the first parameter measurables Is a list of sub items to be measured , and constraints Is a constraint from the parent .
The example effect is as follows :
In addition, there is a customized Waterfall flow layout , If you are interested, you can have a look at .
design sketch :
Layout direction
If you need to change the orientation of the layout , have access to LocalLayoutDirection Realization . Support to modify the layout direction :Ltr( From left to right )、Rtl( Right to left ).
Here's an example :
/**
* 3. Layout direction
*/
@Composable
fun ChangeColumnDirection(){
CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl ) {
Column(Modifier.fillMaxWidth()) {
Text("Title")
Text("Subtitle")
}
}
}
Effect of the sample :
This is the end of the custom layout , Relatively little content .
边栏推荐
- 【mysql学习笔记21】存储引擎
- Vscode attempted to write the procedure to a pipeline that does not exist
- How to "transform" small and micro businesses (II)?
- [shared farm] smart agriculture applet, customized development and secondary development of Kaiyuan source code, which is more appropriate?
- Encoding format for x86
- Use Navicat to compare data differences and structure differences of multi environment databases, and automatic DML and DDL scripts
- With the QQ group file storage function of super nice, you immediately have n cloud disks that are easy to download and never expire
- Creating a binary tree (binary linked list) from a generalized table
- Analysis on the thinking of 2022 meisai C question
- Wearable devices may reveal personal privacy
猜你喜欢

Huipay international permet au commerce électronique transfrontalier de devenir une plate - forme de paiement transfrontalière conforme!

How to delete a blank page that cannot be deleted in word

Creo makes a mobius belt in the simplest way

Puzzle (019.2) hexagonal lock
![[zufe school competition] difficulty classification and competition suggestions of common competitions in the school (taking Zhejiang University of Finance and economics as an example)](/img/ee/2b8aebc1c63902d4d85ff71fd45070.jpg)
[zufe school competition] difficulty classification and competition suggestions of common competitions in the school (taking Zhejiang University of Finance and economics as an example)

Learning notes of rxjs takeuntil operator

纳米数据世界杯数据接口,中超数据,体育数据比分,世界杯赛程api,足球比赛实时数据接口

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

Reasons for Meiye to choose membership system
![[matlab] image binarization (imbinarize function)](/img/3e/066f460d9f436bbc43ea35e46093e2.jpg)
[matlab] image binarization (imbinarize function)
随机推荐
[MySQL learning notes 21] storage engine
Ruiji takeout project (II)
Force buckle -104 Maximum depth of binary tree
Online notes on Mathematics for postgraduate entrance examination (9): a series of courses on probability theory and mathematical statistics
Voiceprint Technology (I): the past and present life of voiceprint Technology
Rxjs TakeUntil 操作符的学习笔记
PMP考试多少分算通过?
How much money have I made by sticking to fixed investment for 3 years?
Reasons for Meiye to choose membership system
Test Development Engineer
[buuctf.reverse] 121-125
Cocopod error failed: undefined method `map 'for nil:nilclass
Rxjs TakeUntil 操作符的学习笔记
Data-driven anomaly detection and early warning of 21 May Day C
Is GF Securities reliable? Is it legal? Is it safe to open a stock account?
2022 postgraduate entrance examination experience post -- Alibaba Business School of Hangzhou Normal University -- management science and Engineering (including the recommendation of books and course
Fcpx quickly add subtitles | Final Cut Pro import fcpxml subtitle file does not match the video time? I got it in code
Can two Mitsubishi PLC adopt bcnettcp protocol to realize wireless communication of network interface?
Learning notes of rxjs takeuntil operator
Grabcut image segmentation in opencv