简体   繁体   English

Jetpack Compose:如果文本不合适,使用不同的布局?

[英]Jetpack Compose: Use different layout if text does not fit?

Say I have a fixed size rectangle with some text inside.假设我有一个固定大小的矩形,里面有一些文字。 Since the user can change the font size from the System - Accessibility settings on the device, the font might not fit inside the fixed sized rectangle.由于用户可以从设备上的系统 - 辅助功能设置更改字体大小,因此字体可能不适合固定大小的矩形。 If this happen, we would like to render the text outside the rectangle instead.如果发生这种情况,我们希望将文本呈现在矩形之外。

AFAIK I should somehow measure the text's width (for example) and see if it fits inside the rectangle and if not, layout the components in a different manner. AFAIK 我应该以某种方式测量文本的宽度(例如),看看它是否适合矩形,如果不适合,则以不同的方式布局组件。

How would I do this in Jetpack Compose?我将如何在 Jetpack Compose 中执行此操作?

So with this pseudo code, if text does not fit inside the Box I would like to lay out the text below it, thus introducing a Column etc instead.因此,使用此伪代码,如果text不适合Box内,我想在其下方布置文本,从而引入Column等。

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

Using onTextLayout you can get size of drawn text.使用onTextLayout您可以获得绘制文本的大小。

To prevent actually drawing it while calculating the size you can use drawWithContent modifier.为了防止在计算大小时实际绘制它,您可以使用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()
        }
    }
}

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/cdp

https://github.com/mbpatel6245/csp https://github.com/mbpatel6245/csp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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