开发者

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 A-B How to implement this ? thanks

name = (EditText)findVi开发者_高级运维ewById(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) {
        }

    });


Add a TextWatcher, using addTextChangedListener().


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

               }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜