简体   繁体   English

每次更改后Android-Change Edittext

[英]Android-Change Edittext after each change

how can i add Char such as this dash '-' after each change in edtitext for example if the user enter A then the text in edittext will be A- then the user will complete and enter Char B then the edittext will be AB How to implement this ? 如何在edtitext中每次更改后添加如此短划线' - '的字符,例如,如果用户输入A,则edittext中的文本将为A-然后用户将完成并输入字符B然后编辑文本将是AB如何实现这个? thanks 谢谢

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){


               }

You are having infinite loop as described in Android Doc 您正在使用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. 但要注意不要陷入无限循环,因为您所做的任何更改都会导致以递归方式再次调用此方法。

So all you have to do is just imposing a condition to avoid infinite loop. 所以你要做的只是强加条件以避免无限循环。 For example, 例如,

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) {
        }

    });

Append the - char in beforeTextChagned beforeTextChagned附加- char

  name = (EditText)findViewById(R.id.editText1);
  name.addTextChangedListener(new TextWatcher() {
         public void beforeTextChanged(CharSequence s, int start, int count, int after) {
             name.setText(s+"-");
         }
         public void afterTextChanged(Editable s){}
         public void onTextChanged(CharSequence s, int start, int before, int count){}
  }
    name = (EditText)findViewById(R.id.editText1);
            name.addTextChangedListener(new TextWatcher(){
                 public void afterTextChanged(Editable s) {
               try{    
                     name.setText(s.toString()+"-");
               }catch(exception e)
              {
               e.printStackTrace();
              } 
                    }
         public void beforeTextChanged(CharSequence s, int start, int count, int after){}
           public void onTextChanged(CharSequence s, int start, int before, int count){

               }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM