Search code examples
androidandroid-layoutuser-interfaceandroid-jetpackandroid-jetpack-compose

Compose TextField clears value on gaining focus


I have a Composable function which displays 2 TextFields. Here's my code:

fun CreateEntryItem() {

    var wordA by remember { mutableStateOf("") }
    var wordB by remember { mutableStateOf("") }

    Column {
        Row {
            TextField(
                value = wordA,
                onValueChange = { wordA = it },
                enabled = true,
                modifier = Modifier.weight(1f)
            )
            TextField(
                value = wordB,
                onValueChange = { wordB = it },
                enabled = true,
                modifier = Modifier.weight(1f)
            )
        }
    }
}

When I give focus to TextField A, I can type and the value of wordA updates correctly.

Here's the weird behaviour:

I then give focus to TextField B. I then give focus back to TextField A. When I start typing, instead of TextField A inserting / appending characters at the cursor position in the existing text, it completely clears the existing text (as set pre-focus), and 'starts afresh'. That is to say, each TextField only remembers text entered in the current 'focus session'.

Am I doing this wrong? Or is this a bug in Compose? I reproduced this behaviour on both 1.0.0-beta07 and 1.0.0-beta08.


Solution

  • Turns out this isn't a Compose bug per se, but an emulator issue. Running the exact same code on a real device didn't run into this issue.

    The emulator that encountered this issue was API 30 running on macOS Big Sur. I haven't tested whether other systems are also affected by this emulator bug.