美文网首页
RecyclerView Adapter中EditText监听文

RecyclerView Adapter中EditText监听文

作者: 阡陌昏晨 | 来源:发表于2022-05-12 15:01 被阅读0次

    adapter中每一个item都有一个EditText 但是需要每一个EditText添加TextWatcher。一旦你在原来的基础上 新增一个item 就会导致前面的EditText会监听到新增的EditText输入。结果就是输入值会错乱。
    解决思路:就是每次给Item设置tag 一旦item被移除就移除removeTextChangedListener 监听。保证只有一个EditText监听输入。

    代码核心如下,BaseQuickAdapter 大家搜索一下就知道了

    class AddProductAdapter :
        BaseQuickAdapter<AddProductResModel, BaseViewHolder>(R.layout.item_add_product) {
    
        override fun onViewDetachedFromWindow(holder: BaseViewHolder) {
            super.onViewDetachedFromWindow(holder)
    
            val etNum = holder.getView<AppCompatEditText>(R.id.et_num)
            if (etNum != null && etNum.tag is TextWatcher) {
                etNum.removeTextChangedListener(etNum.tag as TextWatcher)
            }
        }
    
        override fun convert(helper: BaseViewHolder, item: AddProductResModel) {
            val tvSelect = helper.getView<AppCompatTextView>(R.id.tv_select)
            val etNum = helper.getView<AppCompatEditText>(R.id.et_num)
            etNum.requestFocus()
            if (TextUtils.isEmpty(item.name)) {
                tvSelect.text = "请选择项目"
            } else {
                tvSelect.text = item.name
            }
            if (TextUtils.isEmpty(item.value)) {
                etNum.setText("1")
            } else {
                etNum.setText(item.value)
            }
            if (etNum.tag is TextWatcher) {
                etNum.removeTextChangedListener(etNum.getTag() as TextWatcher)
            }
            val textWatcher = object : TextWatcher {
                override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                }
    
                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
    
                }
    
                override fun afterTextChanged(s: Editable?) {
                    item.value = s.toString()
                }
            }
            etNum.addTextChangedListener(textWatcher)
            etNum.tag = textWatcher
    
            helper.addOnClickListener(R.id.ll_project)
            helper.addOnClickListener(R.id.rl_delete)
    
        }
    
    public class AddProductResModel {
        public String code;
        public String name;
        public String value;
    }
    

    相关文章

      网友评论

          本文标题:RecyclerView Adapter中EditText监听文

          本文链接:https://www.haomeiwen.com/subject/mfosurtx.html