Add character automatically to EditText after 6 letters

I want to automatically put a “-” after 6 letters in my EditText, and I want the user to continue to write after the “-”. (I want the user to write: 1234562 and he appears 123456-2 in EditText).

But I do not know how to do it, and if it is possible. If you can help me, thanks

+6
source share
5 answers

You can add TextChangedListener to EditText. Please refer to this post: fooobar.com/questions/65305 / ...

+2
source

Add textwatcher . Then use the following code:

@Override public void afterTextChanged(Editable text) { if (text.length() == 6) { text.append('-'); } } 

You can also use several conditions in the if statement:

  if (text.length() == 3 || text.length() == 6) { text.append('-'); } 
+11
source
 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
source
 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) { } }); 
+2
source

You can also remove characters with this:

 text.addTextChangedListener(new TextWatcher() { int first = 0; int second; @Override public void afterTextChanged(Editable s) { second = first; first = s.length(); if(text.length()==6 && first>second){ text.append("-"); } } 
0
source

Source: https://habr.com/ru/post/972830/


All Articles