I'm trying to make editText, where I am inserting some text. After each three characters,I want to insert dash.
Example:
Type: 123
Result:123-
Now when cursor is behind dash and you press delete, I want to delete dash and character behind dash. For example:
123-
result after delete key: 12. How to do it. Thank you for advice.
EDIT
my code is:
EditText editText;
boolean keyDel = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
editText.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL) {
keyDel = true;
}
return keyDel;
}
});
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String str = s.toString();
System.out.println(str.length());
if (str.length() == 3) {
str = str + "-";
} else if (str.length() == 7) {
str = str + "-";
} else if (str.length() % 4 == 0 && keyDel == true) {
str = str.substring(0, str.length() - 2);
} else {
return;
}
editText.setText(str);
editText.setSelection(editText.getText().length());
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
I found Android 4.4.2 and higer doesn´t support keyevent.
I'm rather new to android programming myself. Nevertheless, I think that everytime you call "setText" you are trigging a new onTextChanged event. In my app I remove the listener, set the text and then add the listener again in order to avoid this problem. But for doing this you'll have to save the reference to the TextWatcher.
I.e. given your Activity extends TextWatcher:
You can also put the cursor at the end using:
onTextChanged is called everytime you add and remove something. So if your String has length 3, you add your - and the new length is 4. If you press delete (new length is 3 again), onTextChanged is called and - is added again. SO only add something if nothing has been removed from the text.
I was inspired by this answer to achieve what you want: