I've come across a strange compose issue. It's ei...
# compose
j
I've come across a strange compose issue. It's either a bug, or I'm not understanding something about compose. This code works as expected. The println only prints when the text value changes or the user moves the cursor
Copy code
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:
Copy code
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. Any ideas?
j
I think it might have something to do with the spans your IME adds. Placing the cursor in a word makes the IME add spans for editing (to mark which part of the text should be replaced when autocorrect triggers). Because you only copy over the text, the IME keeps re-adding its spans. What you could do, and I generally consider this a better approach for manipulating editable text styles, is using
VisualTransformation
. The spans you add there are not interfered with by the IME.
j
Ah that makes so much sense that it's from IME! I wasn't aware of the
VisualTransformation
interface. I'm using that now and it works well. Thank you!
🎉 1