Scenario:
A sign up page with username and password edittexts.
Enable password only when username entered is valid.
Layout XML:
<com.google.android.material.textfield.TextInputLayout
...>
<androidx.appcompat.widget.AppCompatEditText
android:id="@+id/username_edit_text"
android:inputType="text"
android:onTextChanged="@{model::onUsernameTextChanged}"
.../>
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
...>
<androidx.appcompat.widget.AppCompatEditText
android:id="@+id/sign_in_fragment_password_edit_text"
android:enabled="@{safeUnbox(model.isUsernameValid)}"
android:focusable="@{safeUnbox(model.isUsernameValid)}"
android:inputType="textPassword"
android:onTextChanged="@{model::onPasswordTextChanged}"
.../>
</com.google.android.material.textfield.TextInputLayout>
View model:
var isUsernameValid: ObservableField<Boolean> = ObservableField(false)
// On username text changed
fun onUsernameTextChanged(usernameString: CharSequence, start: Int, before: Int, count: Int) {
// Update username validity
isUsernameValid.set(usernameString.length >= 8)
}
The observable field isUsernameValid
is updated in onUsernameTextChanged()
in the view model.
Problem with the above code:
Password editext is enabled when valid username is entered but the edittext is not focusable.
Removing android:focusable="@{safeUnbox(model.isUsernameValid)}"
makes the edittext gain focus even if no valid username is entered by using soft keyboard next action.