2
0

More than 1 year has passed since last update.

Jetpack Composeで画面幅を取得して4分割する方法

Posted at

はじめに

今回はまず画面の幅を取得して、その上で最小値を設定して4分割した値を取得し、Jetpack ComposeのRowの中でそれぞれ要素に横幅を設定して呼び出していこうと思います。

画面の幅を取得

まず、画面の横幅を取得するところからやっていこうと思います。


@Composable
fun Root() {
  DetailSection(
    modifier = Modifier
      .fillMaxWidth()
  )
}


@Composable
fun DetailSection(
  modifier: Modifier = Modifier
) {
  val configuration = LocalConfiguration.current.screenWidthDp.dp
  
  Row(
    modifier = modifier,
    horizontalArrangement = Arrangement.Start,
    verticalAlignment = Alignment.CenterVertically
  ) {
    DetailSectionButton(
      modifier = Modifier
    )
  }
}

上のval configuration = LocalConfiguration.current.screenWidthDp.dpで画面の横幅を取得しています。

左右のpaddingと最小値の設定 

次に最小値を設定していこうと思います。 

@Composable
fun DetailSection(
  modifier: Modifier = Modifier
) {
  val screenWidth = LocalConfiguration.current.screenWidthDp.dp
  val minWidth = dimensionResource(id = R.dimen.section_width) // 80dp
  val buttonWidth = (screenWidth * (1F / 4F)).coerceAtLeast(minWidth)
  
  Row(
    modifier = modifier,
    horizontalArrangement = Arrangement.Start,
    verticalAlignment = Alignment.CenterVertically
  ) {
    DetailSectionButton(
      modifier = Modifier
        .width(buttonWidth)
    )
    ......
  }
}

val minWidth = dimensionResource(id = R.dimen.section_width)で最小値を取得して、
val buttonWidth = (screenWidth * (1F / 4F)).coerceAtLeast(minWidth)で、buttonWidthの値を80dpに設定しています。 
あとはこれを、各コンポーネントに渡していけば完了です!

以上です🫡

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0