0

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.

Abhimanyu
  • 11,351
  • 7
  • 51
  • 121
  • @SumitShukla I am not doing anything in activity, everything is done in viewmodel. Updated my viewmodel code with text changed methods. – Abhimanyu Jul 21 '19 at 08:45

1 Answers1

0

First of all make use of:

<com.google.android.material.textfield.TextInputEditText/> 

instead of:

<androidx.appcompat.widget.AppCompatEditText/>

For this problem : Password editext is enabled when valid username is entered but the edittext is not focusable.

Use editText.requestFocus() to make edittext focused after enabling it. Also consider using TextWatcher for edittext to simplify validation purposes.

Sumit Shukla
  • 4,116
  • 5
  • 38
  • 57