Home > Enterprise >  reveal parts of text without causing a recomposition?
reveal parts of text without causing a recomposition?

Time:01-23

I'm basically writing a small quiz game with android jetpack compose in which you've got a question displayed and a text field below, I wanted to implement a "hint" (which appears under the text field and shows more and more of the correct answer for every bad answer). After implementing it, it causes a recomposition which selects a new question. Thus a question arrives, is there a way to update just the "hint" part of the screen or is that impossible ? (this might sound stupid but maybe I've missed something and there is a way) Thanks in advance for every comment :)

CodePudding user response:

You can recompose any part of a UI (without recomposing the entire screen or unrelated parts of the screen) as long as you isolate that section and only apply state changes to those parts that you want updated. The value you apply to your hint text should come from a viewmodel that contains a mutable state variable containing the text you want to update the hint with:

class MyViewModel : ViewModel() {
    var hintText = mutableStateOf("")

    fun onTextFieldChange(answer: String) {
        // Retrieve your hint text from whatever api handles the user's response.
        hintText.value = processAnswer(answer)
    }
}

@Composable
fun Question() {
    val vm = MyViewModel()
    var text by remember { mutableStateOf("") }

    Column(modifier = Modifier.fillMaxWidth()) {
        TextField(
            value = text,
            onValueChange = {
                text = it
                vm.onTextFieldChange(it)
            },
            label = { Text("Label") },
            singleLine = true
        )

        HintText(vm = vm)
    }
}

@Composable
fun HintText(
    vm: MyViewModel
) {
    Text(text = vm.hintText.value)
}
  •  Tags:  
  • Related