Search code examples
androidandroid-textinputlayout

How can I see if the endIcon in a TextInputLayout is checked?


There is an isEndIconChecked() in the EndCompoundLayout but I cannot see any access method to it from the TextInputLayout.

Whats the best way to detect if it is currently checked or not?

In my case I want a "Repeat password" input only be visible when the "password_toggle" end mode is not checked.

I looked into the source code and are now using as a workaround:

    binding.loginPassword.setEndIconOnClickListener {
        binding.loginPassword.editText?.apply {
            transformationMethod =
                if (transformationMethod is PasswordTransformationMethod) null
                else PasswordTransformationMethod.getInstance()
            binding.repeatPassword.isVisible = transformationMethod != null
        }
    }

Solution

  • Update: Combined with answer from Vsevolod, I am now using this helper functions:

    @SuppressLint("DiscouragedApi", "ClickableViewAccessibility")
    private fun registerPasswordCheck(view: TextInputLayout, update: () -> Unit) {
        val endIconViewId = resources.getIdentifier(
            "text_input_end_icon",
            "id",
            requireActivity().packageName
        )
        passwordShownCheck = view.findViewById(endIconViewId)
        passwordShownCheck.setOnTouchListener { _, event ->
            if (event.actionMasked == MotionEvent.ACTION_DOWN) update()
            false
        }
    }
    
    @SuppressLint("RestrictedApi")
    private fun isPasswordShownChecked() = passwordShownCheck.isChecked
    
    private lateinit var passwordShownCheck: CheckableImageButton
    

    Can be called with something like:

    registerPasswordCheck(binding.newPassword) {
        binding.repeatPassword.isVisible = !isPasswordShownChecked()
    }
    

    This way the only internal from the API that is needed is the text_input_end_icon resource and the normal behavior of the password toggle does not have to be changed.