10

I would like to understand how is better to use dp and sp values in the Compose project. I checked several open-source Compose projects, and most of them are hardcoding the dimensions. But it's definitely not a way to support flexibility and different screen sizes. I see a few ways for now:

  1. Using the old way with dimens.xml and get the values directly in the compose functions calling dimensionResource().
  2. Having references to the values of dimens.xml in a Kotlin class. For example:
class AppDimensions {
  val paddingSmall: Dp
       @Composable
       get() = dimensionResource(R.dimen.padding_small)
  ...
}
  1. Not to use the dimens.xml and implement your own logic for different screen sizes. For example:
class AppDimensions {
  val paddingSmall = when(screenSize) {
      Compact -> 10.dp
      Medium -> 16.dp
      Expanded -> 20.dp
      else -> 10.dp
  }
  ...
}

I like the 3rd variant because it seems more flexible and allows us to avoid returning to XML. But it will require efforts to support it.

But maybe, can we use it in some more convenient way?

Scott Stanchfield
  • 29,742
  • 9
  • 47
  • 65
sergpetrov
  • 1,506
  • 1
  • 11
  • 20

1 Answers1

7

I am using this way in compose;

val LocalDim = compositionLocalOf { Dimensions() }

data class Dimensions(
    val default: Dp = 0.dp,
    val spaceXXSmall: Dp = 2.dp,
    val spaceExtraSmall: Dp = 4.dp,
    val spaceSmall: Dp = 8.dp,
    val spaceMedium: Dp = 16.dp,
    val spaceLarge: Dp = 32.dp,
    val spaceExtraLarge: Dp = 64.dp,
    val spaceXXLarge: Dp = 128.dp,
    val spaceXXXLarge: Dp = 256.dp
}

for use;

val dimensions = LocalDim.current
commandiron
  • 1,019
  • 1
  • 9
  • 25
  • 4
    I'm adding this nice article on top of this answer https://proandroiddev.com/supporting-different-screen-sizes-on-android-with-jetpack-compose-f215c13081bd – Gastón Saillén Sep 14 '22 at 20:22
  • 1
    @commandiron thanks! But how do you manage different screen sizes with this implementation? – sergpetrov Sep 14 '22 at 20:32
  • @sergpetrov I have a few knowledge but I don't have much experience about different screen sizes that's why I don't add. if you found a good article or answer about this i would love to see it. – commandiron Sep 17 '22 at 20:46