简体   繁体   中英

My binding to a Transformations.map doesn't seem to be working

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!

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!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM