问题描述
我正在使用Android Jetpack的Compose,并且一直在尝试弄清楚如何保存方向更改状态。
我的思路是使类成为ViewModel。当我使用Android的传统API时,这通常可以正常工作。
当信息更改时,我使用了记住{}和mutableState {}来更新UI。 请验证我的理解是否正确...
remember =保存变量并允许通过.value进行访问,这允许对值进行缓存。但是它的主要用途是在更改时不重新分配变量。
mutableState =更改某些内容时更新变量。
许多博客文章都说使用@Model,但是,尝试该方法时导入会出错。 因此,我添加了一个:ViewModel()
但是,我相信我记得{}阻止了此操作按预期进行?
我可以向正确的方向求点吗?
@Composable
fun DefaultFlashCard() {
val flashCards = remember { mutableStateOf(FlashCards())}
Spacer(modifier = Modifier.height(30.dp))
MaterialTheme {
val typography = MaterialTheme.typography
var question = remember { mutableStateOf(flashCards.value.currentFlashCards.question) }
Column(modifier = Modifier.padding(30.dp).then(Modifier.fillMaxWidth())
.then(Modifier.wrapContentSize(Alignment.Center))
.clip(shape = RoundedCornerShape(16.dp))) {
Box(modifier = Modifier.preferredSize(350.dp)
.border(width = 4.dp,color = Gray,shape = RoundedCornerShape(16.dp))
.clickable(
onClick = {
question.value = flashCards.value.currentFlashCards.answer })
.gravity(align = Alignment.CenterHorizontally),shape = RoundedCornerShape(2.dp),backgroundColor = DarkGray,gravity = Alignment.Center) {
Text("${question.value}",style = typography.h4,textAlign = TextAlign.Center,color = White
)
}
}
Column(modifier = Modifier.padding(16.dp),horizontalGravity = Alignment.CenterHorizontally) {
Text("Flash Card application",style = typography.h6,color = Black)
Text("The following is a demonstration of using " +
"Android Compose to create a Flash Card",style = typography.body2,color = Black,textAlign = TextAlign.Center)
Spacer(modifier = Modifier.height(30.dp))
Button(onClick = {
flashCards.value.incrementQuestion();
question.value = flashCards.value.currentFlashCards.question },shape = RoundedCornerShape(10.dp),content = { Text("Next Card") },backgroundColor = Cyan)
}
}
}
data class Question(val question: String,val answer: String) {
}
class FlashCards: ViewModel() {
var flashCards = mutableStateOf( listOf(
Question("How many Bananas should go in a Smoothie?","3 Bananas"),Question("How many Eggs does it take to make an Omellete?","8 Eggs"),Question("How do you say Hello in Japenese?","Konichiwa"),Question("What is Korea's currency?","Won")
))
var currentQuestion = 0
val currentFlashCards
get() = flashCards.value[currentQuestion]
fun incrementQuestion() {
if (currentQuestion + 1 >= flashCards.value.size) currentQuestion = 0 else currentQuestion++
}
}
已解决:
我的问题是在错误的位置实例化了ViewModel。 它需要在Activity中,并需要ViewModelProvider(this).get(x :: class.java)
一个简单的错误,我想Compose毕竟不一样!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)