android - @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()
解决方案
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}")
推荐阅读
- reactjs - 反应状态更新组件,但不是状态
- python - 使用 groupby 应用到 DataFrame 的函数的重复结果
- java - 推动成本 - 方法
- javascript - 面向 Web 开发人员的专业 javascript 告诉我们如何将对象转换为数字是错误的吗?
- python - python ctypes OSError:异常:访问冲突读取0x008B1000
- gitlab - 如何从 shell 连接到组的 gitlab 项目
- reactjs - 为什么我的 React-Native 组件没有渲染?
- python - 从另一个类的方法动态创建 scipy.stats 分布
- python - 合并列中的类别
- html - Min-height:100vh 不适用于我的项目