How to remove all listeners added with addTextChangedListener

前端 未结 11 1563
谎友^
谎友^ 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条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 17:01

    There is no way to do this using current EditText interface directly. I see two possible solutions:

    1. Redesign your application so you always know what TextWatcher are added to particular EditText instance.
    2. Extend EditText and add possibility to clear all watchers.

    Here is an example of second approach - ExtendedEditText:

    public class ExtendedEditText extends EditText
    {   
        private ArrayList mListeners = null;
    
        public ExtendedEditText(Context ctx)
        {
            super(ctx);
        }
    
        public ExtendedEditText(Context ctx, AttributeSet attrs)
        {
            super(ctx, attrs);
        }
    
        public ExtendedEditText(Context ctx, AttributeSet attrs, int defStyle)
        {       
            super(ctx, attrs, defStyle);
        }
    
        @Override
        public void addTextChangedListener(TextWatcher watcher)
        {       
            if (mListeners == null) 
            {
                mListeners = new ArrayList();
            }
            mListeners.add(watcher);
    
            super.addTextChangedListener(watcher);
        }
    
        @Override
        public void removeTextChangedListener(TextWatcher watcher)
        {       
            if (mListeners != null) 
            {
                int i = mListeners.indexOf(watcher);
                if (i >= 0) 
                {
                    mListeners.remove(i);
                }
            }
    
            super.removeTextChangedListener(watcher);
        }
    
        public void clearTextChangedListeners()
        {
            if(mListeners != null)
            {
                for(TextWatcher watcher : mListeners)
                {
                    super.removeTextChangedListener(watcher);
                }
    
                mListeners.clear();
                mListeners = null;
            }
        }
    }
    

    And here is how you can use ExtendedEditText in xml layouts:

    
    
    
         
    
    
    

提交回复
热议问题