2

This code works as expected. The println only prints when the text value changes or the user moves the cursor

val testText = remember { mutableStateOf(TextFieldValue()) }
TextField(
    value = testText.value,
    onValueChange = {
        // should only happen when you type or move cursor
        println("onValueChange called")
        testText.value = it.copy(
            annotatedString = buildAnnotatedString {
                append(it.text)
            },
        )
    },
)

However, some strange things happen when I add a style span:

val testText = remember { mutableStateOf(TextFieldValue()) }
TextField(
    value = testText.value,
    onValueChange = {
        // should only happen when you type or move cursor
        println("onValueChange called")
        testText.value = it.copy(
            annotatedString = buildAnnotatedString {
                withStyle(SpanStyle(Color.Blue)) {
                    append(it.text)
                }
            },
        )
    },
)

As I type, if my cursor is located in a word that begins with a letter, then the println is continuously called. But if my cursor is in a word that doesn't start with a letter, then the println acts normal. For example, if my text looks like @john{cursor here} is a person or john 9{cursor here}9 test then it's normal. But if my text looks like john{cursor here} is a person then I get the continuous prints.

Why is this happening?

0

3 Answers 3

1

I found out this is happening due to IME auto suggestions. I got this to work by using the TextField visualTransformation parameters instead of applying the style directly to the TextFieldValue.

Posted on behalf of the question asker

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

Comments

0

You doing it the wrong way. if you want to assign value you can do it like below example

val testText = remember { mutableStateOf(TextFieldValue()) }
    TextField(
        value = testText.value.copy(
            annotatedString = buildAnnotatedString {
                withStyle(SpanStyle(Color.Blue)) {
                    append(testText.value.text)
                }
            },
        ),
        onValueChange = {
            // should only happen when you type or move cursor
            println("onValueChange called")
            testText.value = it
        },
    )

I have tested the code in my Android Studio It is working as in Example 1

1 Comment

"testText.value = it" shouldn't compile since testText is a val
0

You need to provide all three arguments when you copy TextFieldValue -- text (or annotatedString), selection, and composition in order to get acceptable behavior.

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.