状态更改不会重新构成视图

时间:2020-01-13 08:32:05

标签: android android-jetpack-compose

我遇到以下问题,其中计数器变量的状态更改不会触发Text组件的重新组合。任何想法可能是什么问题???

@Model
class CounterState(var counter:Int = 0)

@Composable
fun CounterView(counterState: CounterState){
     Column {
         Text(text= "${counterState.counter}", 
              style=(+typography()).body1)

         Button(text ="Increment", 
                onClick = {counterState.counter++},
                style = ContainedButtonStyle())
    }
}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
        app {
            CounterView(CounterState())
        }
    }
}

1 个答案:

答案 0 :(得分:0)

var counter by +state { 0 } Column { Text( text = "$counter", style = (+typography()).body1 ) Button( text = "Increment", onClick = { counter++ }, style = ContainedButtonStyle() ) }