diff --git a/lib/java/com/google/android/material/datepicker/DateFormatTextWatcher.java b/lib/java/com/google/android/material/datepicker/DateFormatTextWatcher.java index c64833fe8cf..1bb66e5d31e 100644 --- a/lib/java/com/google/android/material/datepicker/DateFormatTextWatcher.java +++ b/lib/java/com/google/android/material/datepicker/DateFormatTextWatcher.java @@ -27,15 +27,14 @@ import com.google.android.material.textfield.TextInputLayout; import java.text.DateFormat; import java.text.ParseException; +import java.text.SimpleDateFormat; import java.util.Date; -import java.util.Locale; abstract class DateFormatTextWatcher extends TextWatcherAdapter { @NonNull private final TextInputLayout textInputLayout; - private final String formatHint; - private final DateFormat dateFormat; + private final SimpleDateFormat dateFormat; private final CalendarConstraints constraints; private final String outOfRange; private final Runnable setErrorCallback; @@ -45,11 +44,10 @@ abstract class DateFormatTextWatcher extends TextWatcherAdapter { DateFormatTextWatcher( final String formatHint, - DateFormat dateFormat, + SimpleDateFormat dateFormat, @NonNull TextInputLayout textInputLayout, CalendarConstraints constraints) { - this.formatHint = formatHint; this.dateFormat = dateFormat; this.textInputLayout = textInputLayout; this.constraints = constraints; @@ -85,7 +83,8 @@ public void onTextChanged(@NonNull CharSequence s, int start, int before, int co textInputLayout.setError(null); onValidDate(null); - if (TextUtils.isEmpty(s) || s.length() < formatHint.length()) { + String datePattern = dateFormat.toPattern(); + if (TextUtils.isEmpty(s) || s.length() < datePattern.length()) { return; } @@ -113,19 +112,20 @@ public void beforeTextChanged(@NonNull CharSequence s, int start, int count, int @Override public void afterTextChanged(@NonNull Editable s) { - // Exclude some languages from automatically adding delimiters. - if (Locale.getDefault().getLanguage().equals(Locale.KOREAN.getLanguage())) { + String datePattern = dateFormat.toPattern(); + if (s.length() == 0 || s.length() >= datePattern.length() || s.length() < lastLength) { return; } - if (s.length() == 0 || s.length() >= formatHint.length() || s.length() < lastLength) { - return; + char nextPatternChar = datePattern.charAt(s.length()); + if (isDelimiter(nextPatternChar)) { + s.append(nextPatternChar); } + } - char nextCharHint = formatHint.charAt(s.length()); - if (!Character.isLetterOrDigit(nextCharHint)) { - s.append(nextCharHint); - } + private boolean isDelimiter(char ch) { + return !(ch >= 'A' && ch <= 'Z') + && !(ch >= 'a' && ch <= 'z'); } private Runnable createRangeErrorCallback(final long milliseconds) {