英文:
Variable not updated in compose
问题
我在Kotlin(Jetpack Compose)中有一个类,其中包含一个名为title的变量和一个更新title的ExoPlayer。
class Player {
var title by mutableStatOf("value")
// 其他代码...
title = "new value"
// 其他代码...
}
在用户界面中,创建了该类的一个实例并显示了标题,但在类中更新后,标题仍然不变。是否可以帮助解决这个问题?
英文:
I have a class in Kotlin (Jetpack compose) with a variable title and an exoplayer that updates the title.
class Player{
var title by mutableStatOf("value")
....
title= "new value"
...
}
@Composable
fun Display(){
val player = Player()
player.title?.let{
Text(it)
}
}
In the user interface an instance of the class is created and the title displayed but it remains unchanged after being updated in the class. Can someone help?
答案1
得分: 1
你忘记了remember
玩家实例。在这里,当您更改title
时,您的可组合将被重新组合,因为它读取标题。但当它被重新组合时,您将使用默认标题创建Player
的新实例。
英文:
You forgot to remember
the player instance. Here, when you change title
, your composable is recomposed because it reads the title. But when it is recomposed, you create new instance of Player
with the default title.
val player = remember { Player() }
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论