Home > Mobile >  How to make growing Text Composable scrollable at specific text length?
How to make growing Text Composable scrollable at specific text length?

Time:12-16

Is it possible to make a growing Text Composable physically scrollable when the text reaches a specific length instead of this happening only when it reaches its container bounds? I want to allow the user to physically scroll the Text Composable above a specific text length before it reaches its container bounds.

Current Composable

val scrollState = rememberScrollState(0)

Text(
    text = growingText,
    modifier = Modifier.horizontalScroll(scrollState),
    color = Color.Gray
)

CodePudding user response:

You have to make sure your text content is big enough to enable the scroll and to do it you have to change the width according to the lenght.

Something like:

val maxCount = 6
var textWidth by remember { mutableStateOf<Int?>(null) }
val widthModifier = textWidth?.let { width ->
    with(LocalDensity.current) {
        Modifier.width( if (text.length >= maxCount)
            (width-30).toDp() //reduce the width to enable the scroll
        else
            width.toDp())
    }
} ?: Modifier

val scrollState = rememberScrollState()

Text(
    text = text,
    modifier = Modifier
        .then(widthModifier)
        .horizontalScroll(state = scrollState),
    color = Color.Gray,
    onTextLayout = { textWidth = it.size.width }
)
  • Related