Search code examples
androidkotlinandroid-edittexttextwatcher

onTextChanged fires twice due to two super class overrides


I make custom view and adding a TextWatcher, but the onTextChanged method is also on TextView. And when i override it, it applies to 2 super classes. Is it possible override only one super class?

class PhoneEditText(context: Context, attrs: AttributeSet?) : AppCompatEditText(context, attrs!!),
    TextWatcher {

    override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}

    override fun onTextChanged(charSequence: CharSequence, start: Int, before: Int, count: Int) {
        Timber.d("onTextChanged count = $count")
    }

    override fun afterTextChanged(editable: Editable) {}

enter image description here


Solution

  • you are inheriting from both AppCompatEditText and implementing the TextWatcher interface this means you are extending the behavior of both the AppCompatEditText class and the TextWatcher interface when you override methods like onTextChanged in your custom class, you are actually overriding them for both the superclasses/interfaces you are extending/implementing.

    class PhoneEditText(context: Context, attrs: AttributeSet?) : AppCompatEditText(context, attrs!!),
        TextWatcher {
    
        private var phoneTextWatcher: TextWatcher? = null
    
        init {
            phoneTextWatcher = object : TextWatcher {
                override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
    
                override fun onTextChanged(charSequence: CharSequence, start: Int, before: Int, count: Int) {
                    Timber.d("PhoneEditText onTextChanged count = $count")
                }
    
                override fun afterTextChanged(editable: Editable) {}
            }
    
            addTextChangedListener(phoneTextWatcher)
        }
    
        // Rest of your class implementation...
    }