首页 > 解决方案 > @Model Jetpack Compose doesn't update UI

问题描述

I am newbie about this. I want to update the click button count at the Text in line 111.

I tested it. The Toast in line 107 changes value when the button is clicked, however, the Text in line 111 does not change when I click the Button.

How can I do it so the Text in line 111 will update the value?

Please see the picture attached. It shows the code.enter image description here

    82 class MainActivity : ComponentActivity() {
    83    override fun onCreate(savedInstanceState: Bundle?) {
    84        super.onCreate(savedInstanceState)
    85
    86        setContent {
    87            TestJPC11Theme {
    88                // A surface container using the 'background' color from the theme
    89                Surface(color = MaterialTheme.colors.background) {
    90                    myUI()
    91                }
    92            }//TestJPC11Theme
    93        }//setContent
    94
    95    }//onCreate(savedInstanceState: Bundle?)
    96 }//MainActivity : ComponentActivity()
    97 //===============================
    98 //===============================
    99 @Composable
   100 fun myUI() {
   101   val clk = ClickCount()
   102   val context = LocalContext.current
   103   Column() {
   104       Button(
   105           onClick = {
   106               clk.cnt = clk.cnt + 1
   107               Toast.makeText(context, "You clicked the Button => ${clk.cnt}", Toast.LENGTH_SHORT).show()
   108           }) {
   109               Text(text = "Button")
   110           }//Button
   111       Text(text = "Click => ${clk.cnt}")
   112   }//Column
   113 }//fun myUI()
   114 //===============================
   115 //===============================
   116 @Model
   117 class ClickCount(var cnt: Int = 0)
   118 //===============================
   119 //===============================
   120 @Preview(showBackground = true)
   121 @Composable
   122 fun DefaultPreview() {
   123    TestJPC11Theme {
   124       myUI()
   125    }//TestJPC11Theme
   126 }//fun DefaultPreview()

标签: androidkotlinandroid-jetpackandroid-jetpack-compose

解决方案


The @Model annotation was deprecated. UsemutableStateOf.

class ClickCount(cnt: Int){
    var cnt by mutableStateOf(cnt)
}

and:

  val clk = remember{ClickCount(0)}
  val context = LocalContext.current
  Button(
   onClick = {
      clk.cnt = clk.cnt + 1
      Toast.makeText(context, "You clicked the Button => ${clk.cnt}", Toast.LENGTH_SHORT).show() }
  ){
      Text(text = "Button")
  }//Button

  Text(text = "Click => ${clk.cnt}")

推荐阅读