Home > Back-end >  Couldn't enable button using xml and data binding
Couldn't enable button using xml and data binding

Time:11-22

I'm want to enable button when repeatPasswordInputEditText is not empty, I tried to enable it with android:enabled="@{!repeatPasswordInputEditText.text.toString().isEmpty()}" but it doesn't work, why ? I'm also calling binding.lifecycleOwner = this in onCreateView

<com.google.android.material.textfield.TextInputLayout
    android:id="@ id/uRepeatPassword"
    android:layout_width="384dp"
    android:layout_height="75dp"
    android:layout_marginStart="16dp"
    android:layout_marginEnd="16dp"
    android:hint="@string/repeat_password_hint"
    app:passwordToggleEnabled="true"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@ id/uNewPassword">

    <com.google.android.material.textfield.TextInputEditText
        android:id="@ id/repeatPasswordInputEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:text="@{passwordChangeViewModel._repeatPassword}"
        android:background="@color/white"
        app:passwordToggleEnabled="false"/>
</com.google.android.material.textfield.TextInputLayout>

<com.google.android.material.button.MaterialButton
    android:id="@ id/changePasswordButton"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Change Password"
    android:enabled="@{!repeatPasswordInputEditText.text.toString().isEmpty()}"
    app:layout_constraintTop_toBottomOf="@ id/uRepeatPassword">
</com.google.android.material.button.MaterialButton>

CodePudding user response:

You cannot listen to changes in EditText text inside the XML itself.

In your code, you have

android:text="@{passwordChangeViewModel._repeatPassword}"

Seems like you are trying to use two-way data-binding here where _repeatPassword is a MutableLiveData<String>. This won't work because it is just one-way right now. You need to replace @ with @= to make it two way. Now that you have two-way data binding working, you can use the value of this live data to enable/disable your button:

android:enabled="@{!_repeatPassword.empty}"

If you are not using two-way data binding, you will have to put the logic in your Activity/Fragment:

repeatPasswordInputEditText.doAfterTextChanged { text ->
    changePasswordButton.enabled = text.isNotEmpty()
}
  • Related