Android-Change Edittext after each change

末鹿安然 提交于 2019-12-10 22:09:49

问题


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


               }

回答1:


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

    });



回答2:


Add a TextWatcher, using addTextChangedListener().




回答3:


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



回答4:


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

               }


来源:https://stackoverflow.com/questions/7459966/android-change-edittext-after-each-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!