每次更改后Android-Change Edittext

时间:2011-09-18 06:52:34

标签: android android-edittext textwatcher

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

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


               }

4 个答案:

答案 0 :(得分:4)

您正在使用Android Doc

中描述的无限循环
  

但要注意不要让自己进入无限循环,因为你所做的任何更改都会导致以递归方式再次调用此方法。

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

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

    });

答案 1 :(得分:1)

答案 2 :(得分:1)

-

中附加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){}
  }

答案 3 :(得分:0)

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

               }