简体   繁体   中英

How to create responsive layouts with Jetpack Compose?

In the traditional view system, I handled responsiveness by using bias/guidelines/weights/wrap_content/avoiding hard coding dimensions/placing views relative to each other in Constraint Layout, using 'sdp' and 'ssp' etc.

How do I create responsive layouts with Jetpack Compose? I've been searching for info regarding it but unable to find.

Please help!

Two things can help you build flexible and responsive layouts in compose.

1 - Use the Weight modifier in Row and Column

A composable size is defined by the content it's wrapping by default. You can set a composable size to be flexible within its parent. Let's take a Row that contains two two Box composables. The first box is given twice the weight of the second, so it's given twice the width. Since the Row is 210.dp wide, the first Box is 140.dp wide, and the second is 70.dp:

@Composable
fun FlexibleComposable() {
    Row(Modifier.width(210.dp)) {
        Box(Modifier.weight(2f).height(50.dp).background(Color.Blue))
        Box(Modifier.weight(1f).height(50.dp).background(Color.Red))
    }
}

This results in:

在此处输入图像描述

2 - Use BoxWithConstraints

In order to know the constraints coming from the parent and design the layout accordingly, you can use a BoxWithConstraints. The measurement constraints can be found in the scope of the content lambda. You can use these measurement constraints to compose different layouts for different screen configurations.

It lets you access properties such as the min/max height and width:

@Composable
fun WithConstraintsComposable() {
    BoxWithConstraints {
        Text("My minHeight is $minHeight while my maxWidth is $maxWidth")
    }
}

Example usage:

BoxWithConstraints {
    val rectangleHeight = 100.dp
    if (maxHeight < rectangleHeight * 2) {
        Box(Modifier.size(50.dp, rectangleHeight).background(Color.Blue))
    } else {
        Column {
            Box(Modifier.size(50.dp, rectangleHeight).background(Color.Blue))
            Box(Modifier.size(50.dp, rectangleHeight).background(Color.Gray))
        }
    }
}

You have also option to manage scalable size of widget and scalable size of font with help of below library. May be that can help you to give option to manage some alternative way.

https://github.com/mbpatel6245/cdp

https://github.com/mbpatel6245/csp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM