我正在使用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毕竟不一样!
答案 0 :(得分:3)
在 Compose 中有另一种处理配置更改的方法,它是 rememberSaveable
。作为docs says:
虽然 remember
可以帮助您在重新组合时保留状态,但不会在配置更改时保留状态。为此,您必须使用 rememberSaveable
。 rememberSaveable
会自动保存可以保存在 Bundle 中的任何值。对于其他值,您可以传入自定义保护程序对象。
似乎 Mohammad's solution 更健壮,但这个似乎更简单。
答案 1 :(得分:-1)
与以前一样,您可以使用体系结构组件ViewModel来保留配置更改。
您应该在Activity / Fragment中初始化ViewModel,然后将其传递给Composable函数。
class UserDetailFragment : Fragment() {
private val viewModel: UserDetailViewModel by viewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return ComposeView(context = requireContext()).apply {
setContent {
AppTheme {
UserDetailScreen(
viewModel = viewModel
)
}
}
}
}
}
然后,您的ViewModel应该通过LiveData或Flow之类的方法公开ViewState
UserDetailViewModel:
class UserDetailViewModel : ViewModel() {
private val _userData = MutableLiveData<UserDetailViewState>()
val userData: LiveData<UserDetailViewState> = _userData
// or
private val _state = MutableStateFlow<UserDetailViewState>()
val state: StateFlow<UserDetailViewState>
get() = _state
}
现在您可以在可组合函数中观察此状态:
@Composable
fun UserDetailScreen(
viewModel:UserDetailViewModel
) {
val state by viewModel.userData.observeAsState()
// or
val viewState by viewModel.state.collectAsState()
}