[英]Jetpack Compose: Use different layout if text does not fit?
假設我有一個固定大小的矩形,里面有一些文字。 由於用戶可以從設備上的系統 - 輔助功能設置更改字體大小,因此字體可能不適合固定大小的矩形。 如果發生這種情況,我們希望將文本呈現在矩形之外。
AFAIK 我應該以某種方式測量文本的寬度(例如),看看它是否適合矩形,如果不適合,則以不同的方式布局組件。
我將如何在 Jetpack Compose 中執行此操作?
因此,使用此偽代碼,如果text
不適合Box
內,我想在其下方布置文本,從而引入Column
等。
@Composable
fun myView() {
val text = Text("Some text")
Box(modifier = Modifier.size(40.dp)) {
text
}
}
使用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()
}
}
}
您還可以選擇在以下庫的幫助下管理小部件的可縮放大小和字體的可縮放大小。 可能這可以幫助您選擇管理一些替代方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.