Home > other >  Material EditText "password_toggle" Icon Visible without focus/data - Android
Material EditText "password_toggle" Icon Visible without focus/data - Android

Time:01-17

I want to hide this Icon of password_toggle when EditText is Blank. Only show this icon when Any data inside this.

Like: clear_text icon work inside Name Section.

Here Blank editText showing icon

I am using app:endIconMode="password_toggle" inside TextInputLayout

<com.google.android.material.textfield.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
            app:endIconMode="password_toggle"
            android:hint="Password">

            <com.google.android.material.textfield.TextInputEditText
                android:id="@ id/edittextPassword"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPassword"
                />
        </com.google.android.material.textfield.TextInputLayout>

CodePudding user response:

You can achieve what you want using a TextWatcher.

If you use Android KTX via implementation "androidx.core:core-ktx:1.9.0"

You will get access to a convenient extension method you can use like this:

edittextPassword.doOnTextChanged { text, start, count, after -> 
    // if text is blank, hide end icon,
    // otherwise, show password toggle
}

Reference: https://developer.android.com/reference/kotlin/androidx/core/widget/package-summary#(android.widget.TextView).doOnTextChanged(kotlin.Function4)

CodePudding user response:

1- put this line on create()

binding.etPasswordLayout.isPasswordVisibilityToggleEnabled = false

2- setText Watcher like this

   binding.edtPassword.addTextChangedListener(object : TextWatcher {
   override fun beforeTextChanged(charSequence: CharSequence, i: Int, 
    i1: Int, i2: Int) {
            binding.etPasswordLayout.isPasswordVisibilityToggleEnabled = 
              true
        }

        override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
        override fun afterTextChanged(editable: Editable) {
        binding.etPasswordLayout.isPasswordVisibilityToggleEnabled = false
     }
      })
  • Related