How to prevent disabled edittext from gaining focus?

177 views Asked by At

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.

1

There are 1 answers

0
Sumit Shukla On

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.