In my App I have a few edit texts for dates
I then Have a text watcher to force the format of DD/MM/YYYY
I also have a a few lines of code to automatically enter the current date
Auto Date code
SimpleDateFormat dateF = new SimpleDateFormat( "dd/MM/yyyy", Locale.getDefault());
String date = dateF.format(Calendar.getInstance().getTime());
dateText.setText(date);
Now My problem is with the text watcher lets say you enter 02/12/2019
and you want to erase the day(02 in this case) you click on the 02 and press backspace
But then for this example if you have 02/12/2019 and you try to erase the 02 you get 01/22/019Y so the digits moves to the left and the cursor jumps to the end of the text like 01/22/019 | Y
So What I want to happen is when you select the text and you erase you only erase the selected text IE the day, month or year in DD/MM/YYYY
Code for my Text Watcher
TextWatcher DateWatcher= new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@SuppressLint("DefaultLocale")
@TargetApi(Build.VERSION_CODES.N)
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@TargetApi(Build.VERSION_CODES.N)
@SuppressLint("DefaultLocale")
@Override
public void afterTextChanged(Editable s) {
if (!s.toString().equals(current)) {
String clean = s.toString().replaceAll("[^\\d.]|\\.", "");
String cleanC = current.replaceAll("[^\\d.]|\\.", "");
int cl = clean.length();
int sel = cl;
for (int i = 2; i <= cl && i < 6; i += 2) {
sel++;
}
if (clean.equals(cleanC)) sel--;
if (clean.length() < 8){
clean = clean + ddmmyyyy.substring(clean.length());
}
else{
int day = Integer.parseInt(clean.substring(0,2));
int mon = Integer.parseInt(clean.substring(2,4));
int year = Integer.parseInt(clean.substring(4,8));
mon = mon < 1 ? 1 : mon > 12 ? 12 : mon;
cal.set(Calendar.MONTH, mon-1);
year = (year<1900)?1900:(year>2100)?2100:year;
cal.set(Calendar.YEAR, year);
day = (day > cal.getActualMaximum(Calendar.DATE))? cal.getActualMaximum(Calendar.DATE):day;
clean = String.format("%02d%02d%02d",day, mon, year);
}
clean = String.format("%s/%s/%s", clean.substring(0, 2),
clean.substring(2, 4),
clean.substring(4, 8));
sel = sel < 0 ? 0 : sel;
current = clean;
FromDate.setText(current);
FromDate.setSelection(sel < current.length() ? sel : current.length());
}
}
private String current="";
private String ddmmyyyy="DDMMYYYY";
private Calendar cal=Calendar.getInstance();