【问题标题】:@Model Jetpack Compose doesn't update UI@Model Jetpack Compose 不更新 UI
【发布时间】:2021-03-26 03:53:58
【问题描述】:

我是新手。 我想更新第 111 行文本处的点击按钮计数。

我测试过了。单击按钮时,第 107 行中的 Toast 会更改值,但是单击按钮时,第 111 行中的文本不会更改。

我该怎么做才能让第 111 行的文本更新值?

请看附图。它显示了代码。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()

【问题讨论】:

    标签: android kotlin android-jetpack android-jetpack-compose


    【解决方案1】:

    @Model 注释已被弃用。使用mutableStateOf

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

    和:

      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}")
    

    【讨论】:

      猜你喜欢
      • 2023-03-10
      • 2023-01-14
      • 1970-01-01
      • 2022-11-03
      • 1970-01-01
      • 1970-01-01
      • 2022-11-15
      • 1970-01-01
      • 2023-02-26
      相关资源
      最近更新 更多