Reputation: 193
Trying to bind a button's enabled property to a Transformations.map. I can't figure out why it is not working. I believe I am doing the exact the same thing as in this Google Code Lab: https://codelabs.developers.google.com/codelabs/kotlin-android-training-quality-and-states/index.html?index=..%2F..android-kotlin-fundamentals#4
Here is what I got:
private val loginFormState = MutableLiveData<LoginFormState>()
private var _username = ""
var username
get() = _username
set(value) {
if(value == _username) return
_username = value
validateFormState()
}
private var _password = ""
var password
get() = _password
set(value) {
if(value == _password) return
_password = value
validateFormState()
}
init {
_busy.value = false
}
val loginButtonEnabled: LiveData<Boolean> = Transformations.map(loginFormState) { it.isDataValid }
private fun validateFormState() {
val formState = LoginFormState()
formState.isUsernameValid = username.isNotEmpty()
formState.isPasswordValid = password.isNotEmpty()
loginFormState.value = formState
}
...
...
<Button
android:enabled="@{loginViewModel.loginButtonEnabled}"
android:id="@+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_marginStart="48dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="48dp"
android:layout_marginBottom="64dp"
android:onClick="@{() -> loginViewModel.onLogin()}"
android:text="@string/action_sign_in"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/password"
app:layout_constraintVertical_bias="0.2" />
...
Any help is greatly appreciated!
Upvotes: 0
Views: 437
Reputation: 193
So I just figured it out. I don't know why this works because other bindings were working before just fine, but by setting:
binding.lifecycleOwner = this
It started working. I didn't set it originally because I was working in an Activity and not a Fragment. If anyone knows why this makes it work a comment would be greatly appreciated!!
Upvotes: 3