3

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?

Suneesh Ambatt
  • 1,347
  • 1
  • 11
  • 41
  • 2
    It is not related to your question but `app:passwordToggleDrawable="@drawable/password_toggle_drawable"` and `app:passwordToggleEnabled="true"` are deprecated. Use `app:endIconMode="password_toggle"`. – Gabriele Mariotti Oct 14 '19 at 14:28

1 Answers1

12

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.

LordParsley
  • 3,808
  • 2
  • 30
  • 41
Sandi
  • 2,415
  • 1
  • 13
  • 11