How to update the same EditText using TextWatcher?

前端 未结 4 921
故里飘歌
故里飘歌 2020-12-11 19:30

In my Android application I need to implement a TextWatcher interface to implement onTextChanged. The problem I have is, I want to update the same EditText With

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-11 19:48

    To supplement Zortkun's answer (where the example code is quite broken), this is how you'd use afterTextChanged() to update the same EditText:

    editText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {    
        }
    
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {    
        }
    
        @Override
        public void afterTextChanged(Editable editable) {        
            if (!editable.toString().startsWith("***")) {
                editable.insert(0, "***");
            }        
        }
    });
    

    Get familiar with the Editable interface to learn about other operations besides insert().

    Note that it's easy to end up in an infinite loop (the changes you do trigger afterTextChanged() again), so typically you'd do your changes inside an if condition, as above.

    As afterTextChanged() javadocs say:

    It is legitimate to make further changes to s from this callback, but be careful not to get yourself into an infinite loop, because any changes you make will cause this method to be called again recursively.

提交回复
热议问题