How to remove all listeners added with addTextChangedListener

前端 未结 11 1580
谎友^
谎友^ 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 16:58

    I struggled with a similar problem with a lot of EditTexts in RecyclerView. I solved it by reflection. Call ReflectionTextWatcher.removeAll(your_edittext) before bind views. This piece of code finds all TextWatchers and removes them from the local EditText's list called "mListeners".

    public class ReflectionTextWatcher {
        public static void removeAll(EditText editText) {
            try {
                Field field = findField("mListeners", editText.getClass());
                if (field != null) {
                    field.setAccessible(true);
                    ArrayList list = (ArrayList) field.get(editText); //IllegalAccessException
                    if (list != null) {
                        list.clear();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    
        private static Field findField(String name, Class type) {
            for (Field declaredField : type.getDeclaredFields()) {
                if (declaredField.getName().equals(name)) {
                    return declaredField;
                }
            }
            if (type.getSuperclass() != null) {
                return findField(name, type.getSuperclass());
            }
            return null;
        }
    }
    

    I hope, this will help someone.

提交回复
热议问题