Jetpack撰写视图模型不更新视图



我在Jetpack Compose中创建了一个视图模型,但是当其中的变量更新时,视图不会刷新。

我在这里遵循视图模型指南:https://developer.android.com/jetpack/compose/libraries#viewmodel

SignInWithGoogleViewSignInWithEmailAddressView中,当我点击ClickableText时,signInOrSignUpMethod变量更新,但SignInOrSignUpView不更新。

我错过了什么?

enum class SignInOrSignUpMethod {
Google,
EmailOnly
}

class SignInOrSignUpViewModel: ViewModel() {
var signInOrSignUpMethod: SignInOrSignUpMethod = SignInOrSignUpMethod.Google
}

//SignInOrSignUpView
@Composable
fun SignInOrSignUpView(signInOrSignUpViewModel: SignInOrSignUpViewModel = viewModel()) {
Box {
//Background image
Image(
painter = painterResource(id = R.drawable.sign_in_sign_up_background),
contentDescription = null,
contentScale = ContentScale.FillBounds,
alpha = 0.35F,
modifier = Modifier
.background(Color.White)
)

Column(
modifier = Modifier
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
//App Logo
Image(
painter = painterResource(id = R.drawable.app_logo),
contentDescription = null,
colorFilter = ColorFilter.tint(
(if (isSystemInDarkTheme()) {
Color.White
} else {
Color.Black
})
),
modifier = Modifier
.size(125.dp, 125.dp)
.offset(0.dp, 50.dp)
)
Spacer(modifier = Modifier.height(150.dp))
//Sign In Text
Text(
text = "Sign In",
style = androidx.compose.ui.text.TextStyle(
fontSize = 30.sp,
fontWeight = FontWeight.Bold
)
)

Spacer(modifier = Modifier.weight(1f))

//Sign In Buttons
if (signInOrSignUpViewModel.signInOrSignUpMethod == SignInOrSignUpMethod.Google) {
SignInWithGoogleView()
} else if (signInOrSignUpViewModel.signInOrSignUpMethod == SignInOrSignUpMethod.EmailOnly) {
SignInWithEmailAddressView()
}
}
}
}

@Composable
fun SignInWithGoogleView(signInOrSignUpViewModel: SignInOrSignUpViewModel = viewModel()) {
Text(
text = "Google Sign In",
style = androidx.compose.ui.text.TextStyle(
fontSize = 30.sp,
)
)
ClickableText(
text = AnnotatedString("Continue with email address"),
onClick = {
Log.d("Print", signInOrSignUpViewModel.signInOrSignUpMethod.toString())
signInOrSignUpViewModel.signInOrSignUpMethod = SignInOrSignUpMethod.EmailOnly
}
)
}

@Composable
fun SignInWithEmailAddressView(signInOrSignUpViewModel: SignInOrSignUpViewModel = viewModel()) {
Text(
text = "Email Sign In",
style = androidx.compose.ui.text.TextStyle(
fontSize = 30.sp,
)
)
ClickableText(
text = AnnotatedString("Continue with Google"),
onClick = {
signInOrSignUpViewModel.signInOrSignUpMethod = SignInOrSignUpMethod.Google
}
)
}

我缺少的这一点是在我的ViewModel声明mutableStateOf:

class SignInOrSignUpViewModel: ViewModel() {
var signInOrSignUpMethod: SignInOrSignUpMethod by mutableStateOf(SignInOrSignUpMethod.Google)
}

相关内容

  • 没有找到相关文章

最新更新