How do I put date masks on EditText
of Android, so I get dd/mm/aaaa
?
How do I put date masks on EditText
of Android, so I get dd/mm/aaaa
?
I usually use a Masked Edittext
in this case, where the component does everything for us.
In your case it would look something like this:
<com.vicmikhailau.maskededittext.MaskedEditText
android:id="@+id/initial_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
app:mask="##/##/####"
android:inputType="date" />
Note the mask
attribute, it is the one you will edit as needed.
Android basically does not offer a native class for this type of action, so it is possible to do this using a combination of numbers and special characters.
There are some libs that can do this, such as:
However, the basic rule these libs might be using is to use the addTextChangeListener
method to check what is typed in the text field, EditText
. In this way, take some action every time the ombudsman gets some change.
See below the class Mask
, in which it has a insert
method that receives as a parameter the desired mask ( ##/##/####
) and EditText
and does the treatment using regular expression.
public abstract class Mask {
public static TextWatcher insert(final String mask, final EditText et) {
return new TextWatcher() {
boolean isUpdating;
String oldTxt = "";
public void onTextChanged(
CharSequence s, int start, int before,int count) {
String str = Mask.unmask(s.toString());
String maskCurrent = "";
if (isUpdating) {
oldTxt = str;
isUpdating = false;
return;
}
int i = 0;
for (char m : mask.toCharArray()) {
if (m != '#' && str.length() > oldTxt.length()) {
maskCurrent += m;
continue;
}
try {
maskCurrent += str.charAt(i);
} catch (Exception e) {
break;
}
i++;
}
isUpdating = true;
et.setText(maskCurrent);
et.setSelection(maskCurrent.length());
}
public void beforeTextChanged(
CharSequence s, int start, int count, int after) {}
public void afterTextChanged(Editable s) {}
};
}
private static String unmask(String s) {
return s.replaceAll("[.]", "").replaceAll("[-]", "")
.replaceAll("[/]", "").replaceAll("[(]", "")
.replaceAll("[)]", "");
}
}
How to use:
EditText etDate = (EditText) findViewById(R.id.etDate);
etDate.addTextChangedListener(Mask.insert("##/##/####", etDate));
See also this answer in SOen where you have a solution very close to this.
Here also in the question about CPF / Cnpj mask on Edittext has a solution that works for you, just modify the desired mask.