EditText的On TextChange侦听器出现问题

时间:2020-06-02 07:51:50

标签: android kotlin

在我的Recyclerview的Adapter类中,我做了如下操作:

holder.mEdtDescription.addTextChangedListener(object : TextWatcher {
    override fun afterTextChanged(p0: Editable?) {
    }

    override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
    }

    override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
        listener.onDeleteOrDescribe(position, "" + holder.mEdtDescription.text.toString(), "describe")
    }
})

holder.mIvDelete.setOnClickListener {
    listener.onDeleteOrDescribe(position, "", "delete")
}

mEdtDescription是EditText。

在从回收站中删除一些值时,我的适配器将调用方法onDeleteOrDescribe。 不幸的是,同时onTextChanged也正在调用。

删除东西时如何避免致电onTextChanged

希望您明白这一点。

根据解决方案,我尝试如下禁用textWatcher:

val textWatcher: TextWatcher = object : TextWatcher {
        override fun afterTextChanged(p0: Editable?) {
        }

        override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
        }

        override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            ToastUtil.displayShortDurationToast(mContext,"called")
            listener.onDeleteOrDescribe(
                position,
                "" + holder.mEdtDescription.text.toString(),
                "describe"
            )
        }
    }
    holder.mEdtDescription.addTextChangedListener(textWatcher)

    holder.mIvDelete.setOnClickListener {
        //listener.onDeleteStep(position)
        holder.mEdtDescription.removeTextChangedListener(textWatcher)
        listener.onDeleteOrDescribe(position, "", "delete")
        holder.mEdtDescription.addTextChangedListener(textWatcher)
    }

但是,仍然在调用onTextChange():(

1 个答案:

答案 0 :(得分:1)

您可以尝试暂时禁用TextWatcher:

val textWatcher :  TextWatcher = object : TextWatcher {
    override fun afterTextChanged(p0: Editable?) {
    }

    override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
    }

    override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
        listener.onDeleteOrDescribe(position, holder.mEdtDescription.text.toString(), "describe")
    }
}

holder.mEdtDescription.addTextChangedListener(textWatcher)

holder.mIvDelete.setOnClickListener {
    holder.mEdtDescription.removeTextChangedListener(textWatcher)
    listener.onDeleteOrDescribe(position, "", "delete")
    holder.mEdtDescription.addTextChangedListener(textWatcher)
}