Tobias Gronbach
02/26/2022, 1:19 PMBen Trengrove [G]
02/26/2022, 7:55 PMSiyamed
02/26/2022, 7:58 PMTobias Gronbach
02/28/2022, 2:24 PM@Composable
fun Speechbubble(
width: Dp,
height: Dp,
text: String,
onLayoutSizeChanged: (width: Dp, height: Dp) -> Unit
) {
Box(
modifier = Modifier.width(200.dp).padding(10.dp),
) {
val density = LocalDensity.current
Image(
painterResource(R.drawable.ic_speechbubble), stringResource(
R.string.speechbubble
),
modifier = Modifier.size(
width,
height
),
contentScale = ContentScale.FillBounds
)
Text(
modifier = Modifier.padding(20.dp, 10.dp, 20.dp, 0.dp),
text = text,
color = MaterialTheme.colors.onSurface,
onTextLayout = { result ->
var maxLineWidth = 0f
for (i in 0 until result.lineCount) {
val current = result.getLineRight(i)
if (current > maxLineWidth)
maxLineWidth = current
}
val maxLineWidthDp = with(density) {
maxLineWith.toDp() + 40.dp
}
val lastLineBottom = with(density) {
result.getLineBottom(result.lineCount - 1).toDp() + 40.dp
}
onLayoutSizeChanged(
maxLineWidthDp,
lastLineBottom,
)
}
)
}
}
In the calling composable I update the state of width and height (in my case it's a list because I've multiple bubbles in a column)
State-Variables
val textWidth = remember { mutableStateListOf<Dp>() }
val textHeight = remember { mutableStateListOf<Dp>() }
Updating State-Variables
items.forEachIndexed { index, trainingItem ->
Speechbubble(
width = textWidth[index],
height = textHeight[index],
text = stringResource(trainingItem.question),
onLayoutSizeChanged = { width, height ->
textWidth[index] = width
textHeight[index] = height
}
)
}