2014-07-25 9 views
6

Voglio inserire automaticamente un "-" dopo 6 lettere nel mio EditText e voglio che l'utente possa continuare a scrivere dopo il "-". (Voglio che l'utente scriva: 1234562 e appare 123456-2 nella EditText).Aggiungi carattere automaticamente in EditText dopo 6 lettere

Ma non so come farlo e se è possibile. Se puoi aiutarmi, grazie

+1

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

risposta

2

Puoi aggiungere un TextChangedListener a EditText. Si prega di fare riferimento a questo post: https://stackoverflow.com/a/4172392/1134429

+5

Questo dovrebbe essere un commento e non una risposta. – kgandroid

+0

grazie, ho provato a implementare TextChangedListener ma probabilmente in modo negativo. – odiiil

10

Aggiungi un textwatcher .Poi utilizzare il seguente codice:

@Override 
public void afterTextChanged(Editable text) {  


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


} 

È inoltre possibile utilizzare condizioni multiple nel if come:

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

Testo stringa = editText.getText(). ToString(); if (text.length() == 6) { editText.append ("-"); } dovrebbe essere in inTextChanged (...) {} – Uzair

Problemi correlati