【问题标题】:Jetpack Compose: Use different layout if text does not fit?Jetpack Compose:如果文本不合适,使用不同的布局?
【发布时间】:2021-11-15 15:05:41
【问题描述】:

假设我有一个固定大小的矩形,里面有一些文字。由于用户可以从设备上的系统 - 辅助功能设置更改字体大小,因此字体可能不适合固定大小的矩形。如果发生这种情况,我们希望将文本呈现在矩形之外。

AFAIK 我应该以某种方式测量文本的宽度(例如),看看它是否适合矩形,如果不适合,则以不同的方式布局组件。

如何在 Jetpack Compose 中执行此操作?

所以对于这个伪代码,如果text 不适合Box 我想在它下面布置文本,从而引入Column 等代替。

@Composable
fun myView() {
  val text = Text("Some text")
  Box(modifier = Modifier.size(40.dp)) {
      text
  }
}

【问题讨论】:

    标签: android android-jetpack-compose android-jetpack-compose-text


    【解决方案1】:

    使用onTextLayout可以获取绘制文本的大小。

    为了防止在计算大小时实际绘制它,您可以使用drawWithContent 修饰符。

    var textSize by remember { mutableStateOf<IntSize?>(null) }
    val density = LocalDensity.current
    val maxDimensionDp = remember(textSize) {
        textSize?.let { textSize ->
            with(density) {
                maxOf(textSize.width, textSize.height).toDp()
            }
        }
    }
    val textComposable = @Composable {
        Text(
            "Some text",
            onTextLayout = {
                textSize = it.size
            },
            modifier = Modifier.drawWithContent {
                if (textSize != null) {
                    drawContent()
                }
            }
        )
    }
    when {
        maxDimensionDp == null -> {
            // calculating size.
            // because of drawWithContent it's not gonna be drawn
            textComposable()
        }
        maxDimensionDp < 40.dp -> {
            Box(modifier = Modifier.size(40.dp).background(Color.Red)) {
                textComposable()
            }
        }
        else -> {
            Column(modifier = Modifier.background(Color.Green)) {
                textComposable()
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多