Search code examples
androidandroid-textinputlayoutandroid-textinputedittext

Callback on toggling password in TextInputLayout


I have chosen the TextInputEditText for my password field, for using the toggle password feature.

Here is my xml code:

        <com.google.android.material.textfield.TextInputLayout
        android:layout_width="@dimen/login_width"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="@dimen/password_margin_top"
        app:hintEnabled="false"
        app:passwordToggleDrawable="@drawable/password_toggle_drawable"
        app:passwordToggleEnabled="true">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/my_login_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fontFamily="sans-serif"
            android:hint="@string/password"
            android:inputType="textPassword"
            android:nextFocusDown="@+id/my_login_login"
            android:padding="@dimen/field_padding" />
    </com.google.android.material.textfield.TextInputLayout>

I have to do some other layout changes on the toggling password. Is there any callback available for this in TextInputLayout?


Solution

  • You can call setEndIconOnClickListener on your TextInputLayout:

    textInputLayout.setEndIconOnClickListener { v ->
        // Layout changes here
    }
    

    However, this removes the click listener responsible for toggling the password transformation method. I would suggest just copying the click listener code in PasswordToggleEndIconDelegate and adding your own functionality on top:

    textInputLayout.setEndIconOnClickListener {
        val editText: EditText? = textInputLayout.editText
        // Store the current cursor position
        val selection = editText?.selectionEnd ?: 0
    
        // Check for existing password transformation
        val hasPasswordTransformation = editText?.transformationMethod is PasswordTransformationMethod;
        if (hasPasswordTransformation) {
            editText?.transformationMethod = null
        } else {
            editText?.transformationMethod = PasswordTransformationMethod.getInstance()
        }
    
        // Restore the cursor position
        editText?.setSelection(selection)
    
        // Add additional functionality here
    }
    

    Edit: This method is only available in material library version 1.1.0-alpha04 onwards and, as of writing, 1.1.0 is still in beta.