I want to create a string with the max number of characters allowable in the box.
setContent {
ViewincomposetestTheme {
var size by remember { mutableStateOf(IntSize.Zero) }
var widthdp by remember { mutableStateOf(0.dp) }
BoxWithConstraints(Modifier.fillMaxSize().background(Color.Yellow)) {
val widthOfChar = 13 // how do I find this
var string by remember {
mutableStateOf(
StringBuffer()
.apply {
repeat(maxWidth.value.toInt() / widthOfChar) { append("H") }
}
.toString()
)
}
Text(string)
}
}
}
CodePudding user response:
You can just use the maxWidth
parameter of the BoxWithConstraints
, then convert the obtained dp
value toPx()
. Decide a textsize for the TextField
in sp
and then do whatever calculations you want to do after converting that to Px as well. Max characters will be maxWidth
/ textSize
, roughly.
CodePudding user response:
You can create a separate Text
to calculate the size of a character, which will report you its size with onTextLayout
. Using drawWithContent
you can prevent it from being drawn.
Also in your example you get the width using maxWidth.value.toInt()
: here you get the value of dp
, not pixels. You could convert it using LocalDensity
, but you also get the pixel value directly from BoxWithConstraints
using constraints.maxWidth
.
BoxWithConstraints(
Modifier
.fillMaxSize()
.background(Color.Yellow)
) {
var charWidth by remember { mutableStateOf<Int?>(null) }
val string = remember(maxWidth, charWidth) {
charWidth?.let { charWidth ->
StringBuffer()
.apply {
repeat(constraints.maxWidth / charWidth) { append("H") }
}
.toString()
}
}
Text(
"H",
onTextLayout = {
charWidth = it.size.width
},
modifier = Modifier.drawWithContent { }
)
string?.let {
Text(string)
}
}