2014-07-25 75 views
6

我想在我的EditText中的6個字母后面自動添加一個「 - 」,並且我希望用戶可以在「 - 」之後繼續寫入。 (我想讓用戶寫:1234562,它在EditText中出現123456-2)。在6個字母后自動在EditText中添加字符

但我不知道如何做到這一點,如果有可能的話。如果你能幫助我,謝謝

+1

http://stackoverflow.com/questions/4172242/live-editing-of-users-input/37187857#37187857 – HenryChuang

回答

10

添加textwatcher。然後使用下面的代碼:

@Override 
public void afterTextChanged(Editable text) {  


    if (text.length() == 6) { 
     text.append('-'); 
    } 


} 

您也可以使用多個條件if語句,如:

if (text.length() == 3 || text.length() == 6) { 
     text.append('-'); 
    } 
2
EditText editText = (EditText) findViewById(R.id.search); 

editText.addTextChangedListener(new TextWatcher() {   
        @Override 
        public void onTextChanged(CharSequence s, int start, int before, int count) {         


        }      
        @Override 
        public void beforeTextChanged(CharSequence s, int start, int count, 
          int after) { 
         // TODO Auto-generated method stub       
        }      
        @Override 
        public void afterTextChanged(Editable text) { 
         // TODO Auto-generated method stub       
          if (text.length() == 6) { 
          text.append('-'); 
    } 
        } 
       }); 
2
EditText editText = (EditText) findViewById(R.id.editText1); 
editText.addTextChangedListener(new TextWatcher() { 
    @Override 
    public void afterTextChanged(Editable s) { 
     String text = editText.getText().toString(); 
     if(text.length() == 6){ 
      editText.append("-"); 
     } 
    } 

    @Override 
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { 

    } 

    @Override 
    public void onTextChanged(CharSequence s, int start, int before, int count) { 

    } 
}); 
+0

String text = editText.getText()。toString(); if(text.length()== 6){ editText.append(「 - 」); }應該在inTextChanged(...){} – Uzair

相關問題