1

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

5
  • The code is correct and it should work properly, you might have another issue in your case Commented Mar 4 at 7:40
  • Try adding .horizontalScroll(rememberScrollState()) in modifier if issue still persists Commented Mar 4 at 7:46
  • @MeghLath: Have you actually tried it? It doesn't work for me. Neither does adding horizontalScroll help. Using the new BasicTextField as outlined in my answer, however, seems to help. Commented Mar 4 at 10:19
  • @Megh Lath:At first, I suspected the issue was with my own project, so I created a brand-new project in Android Studio that only contained the code snippet above. However, the issue still persisted. Later, I downloaded the Android team's Compose project, JetCaster, and found the same problem existed there as well. Commented Mar 6 at 2:23
  • Yeah i tried your code snippet and it worked fine for me. I had just placed your code in @Preview composable and it was working fine Commented Mar 6 at 4:16

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.