David Mcrae Jr
07/28/2020, 1:58 PMclass UserViewModel : ViewModel() {
private val _username = MutableLiveData<String>()
val username: LiveData<String>
get() = _username
private val _password = MutableLiveData<String>()
val password: LiveData<String>
get() = _password
init {
setUsername("")
setPassword("")
}
fun setUsername(username: String) {
_username.value = username
}
fun setPassword(password: String) {
_password.value = password
}
}
@Composable
fun LoginView(userViewModel: UserViewModel) {
val context = ContextAmbient.current
Column(
modifier = Modifier.fillMaxWidth().padding(top = Dp(50.0F)),
horizontalGravity = Alignment.CenterHorizontally
) {
FilledTextField(
value = userViewModel.username.toString(),
onValueChange = { it: String ->
userViewModel.setUsername(it)
},
label = { Text(stringResource(id = R.string.username_label)) },
backgroundColor = Color.Transparent,
placeholder = { Text(stringResource(id = R.string.username_placeholder)) },
keyboardType = KeyboardType.Email,
activeColor = colorResource(id = R.color.mastery_main)
)
FilledTextField(
value = userViewModel.password.toString(),
onValueChange = { it: String ->
userViewModel.setPassword(it)
},
label = { Text(stringResource(id = R.string.password_label)) },
backgroundColor = Color.Transparent,
visualTransformation = PasswordVisualTransformation(),
keyboardType = KeyboardType.Password,
activeColor = colorResource(id = R.color.mastery_main)
)
}
}
I have something like this for my login view and believe I’m using the LiveData correctly but I am seeing the object reference in the field and not the string value of username or password, thoughts?John O'Reilly
07/28/2020, 2:13 PMState
(using for example observeAsState
extension function) so that appropriate recomposition is triggered when that state changes. So, in your case you might have
val usernameState = userViewModel.username.observeAsState("")
and then say
FilledTextField(
value = usernameState.value,
onValueChange = { it: String ->
userViewModel.setUsername(it)
},
and with following added to gradle
implementation "androidx.ui:ui-livedata:$compose_version"
David Mcrae Jr
07/28/2020, 2:32 PMobserveAsState("")
on the LiveData fixed the issue, thanks