directory

  • Hello,Jetpack Compose!
  • Jetpack Compose(2) : Layout

A, layout,

The official website describes the Compose layout

Composable functions are the basic building blocks of Compose. A composable function is a function that emits Unit to describe a part of an interface. This function takes some input and generates what is displayed on the screen. See the Compose Idea model documentation for more details on composable items.

A composable function may emit multiple interface elements. However, if you don’t provide guidance on how to arrange these elements, Compose might arrange them in a way you don’t like.

When we try to write code like this

@Composable
fun MainPage(a) {
    Text(text = "Hello,Jetpack Compose!")
    Text(text = "hello,jetpack compose!")}Copy the code

In the preview view, you can see that the two texts overlap

In XML, we can arrange/constrain the position of view elements in various layouts, so inComposeHow to implement?ComposeIs there anything similar toLinearLayout,FrameLaoyout,ConstraintLayoutWhat about the stuff?



The answer is:There must be.

In many cases, you can simply use Compose’s standard layout elements.

The following layout methods can basically meet the daily development layout requirements.

1. Row

Row can be understood as a horizontal LinearLayout pattern in AN Xml layout, for example:

@Composable
fun MainPage(a) {
    Row(){
        Text(text = "Hello")
        Text(text = ",")
        Text(text = "jetpack compose!")}}Copy the code

As you can see from the Row source, we can also pass the following parameters:

@Composable
inline fun Row(
    modifier: Modifier = Modifier,
    horizontalArrangement: Arrangement.Horizontal = Arrangement.Start,
    verticalAlignment: Alignment.Vertical = Alignment.Top,
    content: @Composable RowScope. () - >Unit
){... }Copy the code
parameter type The default value meaning
modifier Modifier Modifier Layout modifier
horizontalArrangement Arrangement.Horizontal Arrangement.Start Horizontal placement of layout children, from the start of the layout to the end of the layout
verticalAlignment Alignment.Vertical Alignment.Top The vertical alignment of layout children is aligned from the top of the layout by default

Such as:

Note that, as with the LinearLayout, views beyond the maximum width or height of the layout Settings will not be visible

2. Column

Column can be understood as the vertical mode of the LinearLayout in the Xml layout, for example:

@Composable
fun MainPage(a) {
    Column(Modifier.padding(Dp(50f))) {
        Text(text = "Hello")
        Text(text = ",")
        Text(text = "jetpack compose!")}}Copy the code

As you can see from the Column source code, we can also pass the following parameters:

@Composable
inline fun Column(
    modifier: Modifier = Modifier,
    verticalArrangement: Arrangement.Vertical = Arrangement.Top,
    horizontalAlignment: Alignment.Horizontal = Alignment.Start,
    content: @Composable ColumnScope. () - >Unit
){... }Copy the code
parameter type The default value meaning
modifier Modifier Modifier Layout modifier
verticalArrangement Arrangement.Vertical Arrangement.Top Layout children are placed vertically, from the top to the bottom of the layout by default
horizontalAlignment Alignment.Horizontal Alignment.Start The layout child level aligns its way horizontally, starting with the layout by default

Column has the same problem as Row, and note that the arguments used to modify Column child placement are different from Row

3. Box

Box can be understood as FrameLayout in Xml layout, for example:

@Composable
fun MainPage(a) {
    Box(Modifier.size(Dp(300f), Dp(150f)),
        contentAlignment = Alignment.Center) {
        Box(modifier = Modifier
            .background(MaterialTheme.colors.error)
            .size(Dp(200f), Dp(100f)))
        Box(modifier = Modifier
            .background(MaterialTheme.colors.secondary)
            .size(Dp(100f), Dp(50f)))
        Text(text = "hello,jetpack compose!")}}Copy the code

As you can see from the Column source code, we can also pass the following parameters:

@Composable
inline fun Box(
    modifier: Modifier = Modifier,
    contentAlignment: Alignment = Alignment.TopStart,
    propagateMinConstraints: Boolean = false,
    content: @Composable BoxScope. () - >Unit
){... }Copy the code
parameter type The default value meaning
modifier Modifier Modifier Layout modifier
contentAlignment Alignment Alignment.TopStart The default alignment in Box
propagateMinConstraints Boolean false Whether the minimum constraint passed should be passed to the content.

4. BoxWithConstraints

To understand the constraints from the parent and design the layout accordingly, you can use BoxWithConstraints. You can find the measurement constraints in the scope of the content lambda.

BoxWithConstraints is used in exactly the same way as Box, except that, as officially stated, constraints can be measured, for example:

@Composable
fun MainPage1(a) {
    BoxWithConstraints {
        Text("My minHeight is $maxHeight while my maxWidth is $maxWidth")}}Copy the code

Within its scope you can get the maximum and minimum width and height information for BoxWithConstraints.

5. ConstraintLayout

ConstraintLayout is simply ConstraintLayout in Xml layout, and let’s look at the official description

ConstraintLayout helps to place composable items on the screen based on their relative position, and is an alternative to using multiple nested rows, columns, boxes, and custom layout elements. ConstraintLayout is useful when implementing larger layouts with complex alignment requirements.

Note: ConstraintLayout is recommended for creating large, complex layouts in View systems because flat View hierarchies perform better than nested views. However, this is not a problem in Compose because it handles deep layout hierarchies efficiently.

Note: Whether ConstraintLayout is used for a particular interface in Compose depends on the developer’s preference. ConstraintLayout is used in Android View systems as a way to build higher-performance layouts, but this is not a problem in Compose. When choosing, consider whether ConstraintLayout helps make composable items more readable and maintainable.

ConstraintLayout is officially available but not recommended for Compose. ConstraintLayout is used in XML to reduce the level of view nesting and thus improve the performance of Android page rendering. The concept of view nesting does not exist in Compose, so ConstraintLayout depends on personal habits and ConstraintLayout to make composable items more readable and maintainable.

Before you use ConstraintLayout, you need to add the following dependencies in build.gradle:

implementation "Androidx. Constraintlayout: constraintlayout - compose: 1.0.0 - alpha08"
Copy the code

ConstraintLayout in Compose supports DSLS:

  • Referencing is usingcreateRefs() 或 createRefFor()Create,ConstraintLayoutEach composable item in needs a reference associated with it.
  • The constraint is useconstrainAs()Modifier, which takes a reference as an argument and lets you specify its constraints in the body lambda.
  • The constraint is uselinkTo()Or any other useful method.
  • parentIs an existing reference that can be used to specify pairsConstraintLayoutConstraints on the composable item itself.

Here’s another example:

@Composable
fun MainPage(a) {
    ConstraintLayout(Modifier.size(200.dp)) {
        val (button, text) = createRefs()
        Button(
            onClick = { },
            modifier = Modifier.constrainAs(button) {
                top.linkTo(parent.top)
                start.linkTo(parent.start)
                end.linkTo(parent.end)
                bottom.linkTo(parent.bottom)
            },
            colors = ButtonDefaults.buttonColors(
                backgroundColor = MaterialTheme.colors.secondary,
                contentColor = Color.White
            )
        ) {
            Text("Button")
        }

        Text("Text", Modifier.constrainAs(text) {
            top.linkTo(button.top)
        })
    }
}
Copy the code

As you can see, the usage is basically the same as in THE XML, with the button constrained to the center of the view and the top of the text aligned to the top of the button.

6. Spacer

A blank view, which does not officially provide the margin attribute in Xml, is probably recommended instead. Such as:

@Composable
fun MainPage(a) {
    Row {
        Box(Modifier.size(100.dp).background(Color.Red))
        Spacer(Modifier.width(20.dp))
        Box(Modifier.size(100.dp).background(Color.Magenta))
        Spacer(Modifier.weight(1f))
        Box(Modifier.size(100.dp).background(Color.Black))
    }
}
Copy the code

Second, the last

A good memory is better than a bad pen. Jetpack Compose series is my own study notes for the first time, which can not only deepen the knowledge consolidation, but also exercise my writing skills. The content in this article is for reference only, if you have any questions, please leave a comment.

Reference 1.

  • Android developers

2. Scroll view

Row and Column can’t be displayed if the fruit view goes beyond the parent view. In Compose, you can implement both LazyRow and LazyColumn, but they do more than just implement view scrolling, so I won’t cover that in this article. LazyRow and LazyColumn are expected to be detailed in subsequent widgets.