How to mask an EditText to show the dd/mm/yyyy date format

后端 未结 9 2452
甜味超标
甜味超标 2020-11-30 18:31

How can I format an EditText to follow the \"dd/mm/yyyy\" format the same way that we can format using a TextWatcher to mask

9条回答
  •  日久生厌
    2020-11-30 19:19

    This answer does not apply a full mask for the remaining untyped digits. However, it is related and is the solution I needed. It works similar to how PhoneNumberFormattingTextWatcher works.

    As you type it adds slashes to separate a date formatted like mm/dd/yyyy. It does not do any validation - just formatting.

    No need for an EditText reference. Just set the listener and it works. myEditText.addTextChangedListener(new DateTextWatcher());

    import android.text.Editable;
    import android.text.TextWatcher;
    
    import java.util.Locale;
    
    /**
     * Adds slashes to a date so that it matches mm/dd/yyyy.
     *
     * Created by Mark Miller on 12/4/17.
     */
    public class DateTextWatcher implements TextWatcher {
    
        public static final int MAX_FORMAT_LENGTH = 8;
        public static final int MIN_FORMAT_LENGTH = 3;
    
        private String updatedText;
        private boolean editing;
    
    
        @Override
        public void beforeTextChanged(CharSequence charSequence, int start, int before, int count) {
    
        }
    
        @Override
        public void onTextChanged(CharSequence text, int start, int before, int count) {
            if (text.toString().equals(updatedText) || editing) return;
    
            String digitsOnly = text.toString().replaceAll("\\D", "");
            int digitLen = digitsOnly.length();
    
            if (digitLen < MIN_FORMAT_LENGTH || digitLen > MAX_FORMAT_LENGTH) {
                updatedText = digitsOnly;
                return;
            }
    
            if (digitLen <= 4) {
                String month = digitsOnly.substring(0, 2);
                String day = digitsOnly.substring(2);
    
                updatedText = String.format(Locale.US, "%s/%s", month, day);
            }
            else {
                String month = digitsOnly.substring(0, 2);
                String day = digitsOnly.substring(2, 4);
                String year = digitsOnly.substring(4);
    
                updatedText = String.format(Locale.US, "%s/%s/%s", month, day, year);
            }
        }
    
        @Override
        public void afterTextChanged(Editable editable) {
    
            if (editing) return;
    
            editing = true;
    
            editable.clear();
            editable.insert(0, updatedText);
    
            editing = false;
        }
    }
    

提交回复
热议问题