androidandroid-jetpack-composeandroid-compose-textfield

Compose BasicTextField, drag cursor text doesn't scroll


I'm using Compose's BasicTextField, and when I drag the cursor, the text doesn't scroll.

var text by remember { mutableStateOf("123456789123456") }

Box(contentAlignment = Alignment.Center) {
    BasicTextField(
        modifier = Modifier
            .width(100.dp)
            .height(40.dp)
            .background(color = Color.LightGray)
            .wrapContentHeight(align = Alignment.CenterVertically),
        textStyle = TextStyle.Default.copy(
            fontSize = 14.sp, fontWeight = FontWeight.Bold,
            textAlign = TextAlign.Center,
        ),
        value = text,
        singleLine = true,
        onValueChange = { text = it },
    )
}

When I drag the cursor, I want the text to scroll along with it. Instead, this is what's happening:

the sample gif


Solution

  • I'm a bit surprised myself that your code does not work, but switching to the new BasicTextField that uses a TextFieldState instead of a String value fixes it:

    val state = rememberTextFieldState("123456789123456")
    
    BasicTextField(
        modifier = Modifier
            .width(100.dp)
            .height(40.dp)
            .background(color = Color.LightGray)
            .wrapContentHeight(align = Alignment.CenterVertically),
        textStyle = TextStyle.Default.copy(
            fontSize = 14.sp, fontWeight = FontWeight.Bold,
            textAlign = TextAlign.Center,
        ),
        state = state,
        lineLimits = TextFieldLineLimits.SingleLine,
    )
    

    Use state.text to access the text field's content. It's backed by a MutableState so you can easily observe it for changes in Compose or by using a snapshotFlow outside of Compose.