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.