其他分享
首页 > 其他分享> > 每次更改后Android-Change Edittext

每次更改后Android-Change Edittext

作者:互联网

如何在edtitext中每次更改后添加此字符“ – ”之类的字符,例如,如果用户输入A,则edittext中的文本将为A-,然后用户将完成并输入字符B,然后编辑文本将为A-B
怎么实现这个?谢谢

name = (EditText)findViewById(R.id.editText1);
        name.addTextChangedListener(new TextWatcher(){
             public void afterTextChanged(Editable s) {

                 name.setText("-");
                }
     public void beforeTextChanged(CharSequence s, int start, int count, int after){}
       public void onTextChanged(CharSequence s, int start, int before, int count){


               }

解决方法:

您正在使用Android Doc中描述的无限循环

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.

所以你要做的只是强加条件以避免无限循环.例如,

name.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
            if(s.charAt(s.length()-1)!='-'){
                s.append("-");
            }

        }

        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
        }

    });

标签:android,android-edittext,textwatcher
来源: https://codeday.me/bug/20190826/1733542.html