EditText inTextInputLayout仅对第一个字母调用onTextChanged两次

问题描述 投票:1回答:1

我正在开发一个开源文本掩蔽器。您可以单击here查看源代码。

我的问题是,当我用TextInputLayout包装自定义编辑文本时,仅对于第一个字母触发两次onTextChanged。然后它按预期工作。

此“两次通话”破坏了我的逻辑。你们知道什么可能是问题吗?由于其他开发人员都在使用它,因此我不想使用hacky解决方案对其进行修复。我需要找出问题所在。

删除文本监视程序后,我手动设置了文本,然后再次添加了文本监视程序。

这是我的主要逻辑;

此方法仅被调用一次;

   private fun initTextWatcher() {
        textWatcher = object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {}
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                masker?.onTextChanged(s, start, count, before)
            }
        }
        addTextChangedListener(textWatcher)
    }

这就是我手动设置文本的方式;

    private fun setEditTextWithoutTriggerListener(newText: String) {
        removeTextChangedListener(textWatcher)
        onTextChangedListener?.invoke(newText) // This is a custom listener. 
        setText(newText)
        setSelection(text?.length ?: 0) // This puts cursor at the end of the text.
        addTextChangedListener(textWatcher)
    }

为了像TextInputEditText一样处理提示位置,我只是将其功能复制到了我的位置。


    override fun getHint(): CharSequence? {
        val layoutHint = getTextInputLayout()?.hint
        return layoutHint ?: super.getHint()
    }

    override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection? {
        val ic = super.onCreateInputConnection(outAttrs)
        if (ic != null && outAttrs.hintText == null) {
            outAttrs.hintText = getHintFromLayout()
        }
        return ic
    }

    private fun getTextInputLayout(): TextInputLayout? {
        var parent = this.parent
        while (parent is View) {
            if (parent is TextInputLayout) {
                return parent
            }
            parent = parent.getParent()
        }
        return null
    }

    private fun getHintFromLayout(): CharSequence? {
        val layout = getTextInputLayout()
        return layout?.hint
    }

并且我的类像TextInputEditText一样扩展了AppCompatEditText。

android android-edittext android-textinputlayout android-textinputedittext
1个回答
0
投票

如果从onCreate()或init()调用addTextChangedListener(),则将调用移至onResume()或以后调用的任何其他函数中,否则在恢复之前会触发onTextChanged()

© www.soinside.com 2019 - 2024. All rights reserved.