How to remove all listeners added with addTextChangedListener

前端 未结 11 1570
谎友^
谎友^ 2020-11-27 16:24

I have a ListView where each row has an EditText control. I want to add a TextChangedListener to each row; one that contains extra dat

11条回答
  •  Happy的楠姐
    2020-11-27 16:51

    If one, like me, deals with ViewHolder, then simply saving a reference to a text watcher upon its creation will not help. Upon reuse the view will get to some other ViewHolder which would not have a reference to that old text watcher, thus one won't be able to delete it.

    Personally i chose to solve problem like @inazaruk, though updated code to Kotlin + renamed class to better reflect it's purpose.

    class EditTextWithRemovableTextWatchers(context: Context?, attrs: AttributeSet?) : TextInputEditText(context, attrs) {
    
        private val listeners by lazy { mutableListOf() }
    
        override fun addTextChangedListener(watcher: TextWatcher) {
            listeners.add(watcher)
            super.addTextChangedListener(watcher)
        }
    
        override fun removeTextChangedListener(watcher: TextWatcher) {
            listeners.remove(watcher)
            super.removeTextChangedListener(watcher)
        }
    
        fun clearTextChangedListeners() {
            for (watcher in listeners) super.removeTextChangedListener(watcher)
            listeners.clear()
        }
    }
    

提交回复
热议问题