[Compose] BoxWithConstraints

devel_liz·2024년 11월 26일

Compose

목록 보기
9/20

BoxWithConstraints란?

  • 부모 레이아웃의 제약 조건(Constraints)을 기반으로 내부에서 UI를 동적으로 구성할 수 있도록 해줍니다.
  • Box 스코프 기능 전부 쓸 수 있음
  • Constraints 정보 제공
    • BoxWithConstraints 내부에서는 maxWidth, maxHeight, minWidth, minHeight 같은 부모의 제약 조건 정보를 사용할 수 있습니다.
  • UI 동적 구성
    • 화면 크기나 특정 조건에 따라 다른 레이아웃을 배치하거나 스타일을 변경할 수 있습니다.

  • Constraints 정보 제공
@Composable
fun Outer() {
    Column {
        Inner()

    }
}

@Composable
fun Inner() {
    BoxWithConstraints {
        Text(text = "maxW: $maxWidth, maxH: $maxHeight, minW: $minWidth, minH: $minHeight")

    }
}


@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    TestComposeTheme {
        Outer()
    }
}

Inner 인자로 modifier를 전달해보자.

  • 기본 값을 Modifier로 지정하자.
  • 파라미터로 받은 modifier를 BoxWithConstrains에 전달하자.
@Composable
fun Outer() {
    Column {
        Inner(modifier = Modifier
            .widthIn(min = 100.dp, max = 350.dp)
            .heightIn(min = 50.dp))

    }
}

@Composable
fun Inner(modifier: Modifier = Modifier) {
    BoxWithConstraints(modifier) {
        Text(text = "maxW: $maxWidth, maxH: $maxHeight, minW: $minWidth, minH: $minHeight")

    }
}

maxHeight 값이 150.dp가 넘을 때만 추가로 텍스트를 출력해보자.

@Composable
fun Outer() {
    Column {
        Inner(modifier = Modifier
            .width(200.dp)
            .height(160.dp))

    }
}

@Composable
fun Inner(modifier: Modifier = Modifier) {
    BoxWithConstraints(modifier) {
        if (maxHeight > 150.dp) {
            Text(text = "길다 길어 ~~", modifier = Modifier.align(Alignment.BottomCenter))
        }
        Text(text = "maxW: $maxWidth, maxH: $maxHeight, minW: $minWidth, minH: $minHeight")

    }
}

Column에 width를 지정해서 제한해보자.

  • Inner에서 width를 200.dp로 줬지만 적용된 것은 Column의 width 150.dp인 것을 확인할 수 있다.
@Composable
fun Outer() {
    Column(modifier = Modifier.width(150.dp)) {
        Inner(modifier = Modifier
            .width(200.dp)
            .height(160.dp))

    }
}

@Composable
fun Inner(modifier: Modifier = Modifier) {
    BoxWithConstraints(modifier) {
        if (maxHeight > 150.dp) {
            Text(text = "길다 길어 ~~", modifier = Modifier.align(Alignment.BottomCenter))
        }
        Text(text = "maxW: $maxWidth, maxH: $maxHeight, minW: $minWidth, minH: $minHeight")

    }
}
profile
Android zizon

0개의 댓글