简体   繁体   中英

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 ? 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

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

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

               }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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