Is there a way to create a preference in a PreferenceFragment that accepts only integer values? I could implement an EditTextPreference and register an OnPreferenceChangeListener in which I could reject the change if the user enters a a string that is not a number, but I would prefer something that is meant for holding only numbers and that does not allow users to enter anything else, maybe showing only a dial pad keyboard.. I don't such a preference exist, since every descendant of Preference is mapped onto a Boolean (CheckBoxPreference), a String (*EditTextPreference) or a String array (MultiSelectListPreference), i.e. there are no preferences mapped onto integers, but maybe some of you can give me an hint or at least tell me if there are better solutions than the one I've proposed above.
Solution proposed by Grey:
EditText editText = ((EditTextPreference)
findPreference("intent_property")).getEditText();
editText.setKeyListener(new NumberKeyListener() {
#Override
public int getInputType() {
// The following shows the standard keyboard but switches to the view
// with numbers on available on the top line of chars
return InputType.TYPE_CLASS_NUMBER;
// Return the following to show a dialpad as the one shown when entering phone
// numbers.
// return InputType.TYPE_CLASS_PHONE
}
#Override
protected char[] getAcceptedChars() {
return new String("1234567890").toCharArray();
}
});
Shorter solution, which does not allow varying the keyboard to dialpad but requires less code:
EditText editText = ((EditTextPreference)
findPreference("intent_property")).getEditText();
editText.setKeyListener(new DigitsKeyListener());
I don't like just one thing about this solution: the user can enter 0000 and it is accepted and saved in the shared preference (which is a String) as "0000".. this requires you to implement a OnSharedPreferenceChangeListener to intercept changes to shared preferences and remove leading zeros in this preference or implement a change listener directly on this preference and return false to refuse numbers with trailing zeros (tell me if there is a better solution to this last problem which does not involve implementing your own Preference). It would be beautiful if we could modify the newValue in OnPreferenceChangeListener..
There is an easier way to do this. Just set in the EditTextPreference in your XML to android:numeric="integer" (you can set it to integer, signed or decimal).
Eclipse (or whatever tool you are working in) won't show you this as a possible attribute, but just write it in your EditTextPreference and clean your project. You will see that it won't give you any errors. :)
After reading the proposed solutions, I still think a custom preference is the way to go. I did read your remark in bold text, but setting up a basic EditTextIntegerPreference is actually super simple and it will solve the remaining issue you have when the user enters for example "0000".
Just a note up front: since you normally want to be able to use preferences in several places in your app, as far as I'm concerned, a proper implementation of an EditTextIntegerPreference would store its value against an Integer. That way you'll be able to retrieve the int value anywhere, without the need to first parse or cast it.
However, to keep this answer to the point and compact, I'm actually going to show an extension of a regular EditTextPreference, which means that under the hood, the value will still be stored as a string. If you're really keen on getting the 'proper' implementation to work, I don't mind writing that up later on. It shouldn't be too tricky though, so you might want to have a crack at it yourself first. :)
public class EditTextIntegerPreference extends EditTextPreference {
private Integer mInteger;
public EditTextIntegerPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
getEditText().setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
}
public EditTextIntegerPreference(Context context, AttributeSet attrs) {
super(context, attrs);
getEditText().setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
}
public EditTextIntegerPreference(Context context) {
super(context);
getEditText().setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
}
#Override public void setText(String text) {
final boolean wasBlocking = shouldDisableDependents();
mInteger = parseInteger(text);
persistString(mInteger != null ? mInteger.toString() : null);
final boolean isBlocking = shouldDisableDependents();
if (isBlocking != wasBlocking) notifyDependencyChange(isBlocking);
}
#Override public String getText() {
return mInteger != null ? mInteger.toString() : null;
}
private static Integer parseInteger(String text) {
try { return Integer.parseInt(text); }
catch (NumberFormatException e) { return null; }
}
}
The reason why this solves the "0000" issue, is that we're simply casting the user typed value to an int before we store it, and plug it back into a string upon retrieval. That means any leading zeroes (except for '0' as a number of course) will automagically disappear.
The 'number' input type will restrict the user to input only enter numbers, so the parseInteger(...) method is mainly present for sanity reasons, although it will catch a NumberFormatException if you try to enter an empty or null string. Again, you can make this more pretty, which I haven't done for now.
i guess u can call getEditText() to get a EditText obj , then call setKeyListener with a NumberKeyListener.
You should use PreferenceActivity which is basically used to show preferences like an xml file. In this activity you can use checkboxes, edit text and save values to preferences.
You can also reopen the dialog when you get an exception after trying to parseInt() the number.
Here is a sample code:
public class MyEditTextPreference extends EditTextPreference {
private EditText _editText;
public MyEditTextPreference(Context context, AttributeSet attrs) {
super(context, attrs);
_editText = getEditText();
}
#Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
try {
Integer.parseInt(_editText.getText().toString());
} catch (NumberFormatException e) {
((Dialog) dialog).show();
}
}
}
Related
I have a big problem with the SharedPreferences in Android. The preferences are adding unwanted chars to one of my string values once the application is closed. Actually it is a configurable escape sequence.
I have a simple setup, a MainActivity containing
#Override
protected void onStart() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
sequence = prefs.getString("escape_sequence", "");
}
And a preferences screen where the value is set. When i open the app go to the prefences screen, set the value correctly to \n\n and go back to the MainActivity the breakpoint is correctly displaying the sequence as Java.lang.String, value(char[2])= "\n\n", count=2. When i am now restarting the app through android studio the same breakpoint in the code suddenly displays: Java.lang.String, value(char[6])= "\n\n ", count=6, containing 4 Space and 10 escape \u0000 characters.
Can anybody why this is happening and what i can do about that?
BTW i'm not touching the SharedPreferences.Editor anywhere in the App so far. I is strictly done via the PreferencesScreen. So no overwrite is done anywhere in the app. The default values shouldn't be applied either, however the setting is android:defaultValue="\n\n" anyway.
EDIT:
I found the reason: android adds the spaces if a newline is at the end of the preference. I have no idea why.
EDIT:
Here is the custom preference code:
public class SequencePreference extends DialogPreference {
EditText sequenceInput;
public SequencePreference(Context context, AttributeSet attrs) {
super(context, attrs);
setDialogLayoutResource(R.layout.dialog_preference_sequence);
setPositiveButtonText(R.string.settings_sequence_ok);
setNegativeButtonText(R.string.settings_sequence_cancel);
setDialogIcon(null);
}
#Override
protected View onCreateDialogView() {
View view = super.onCreateDialogView();
sequenceInput= (EditText)view.findViewById(R.id.sequence_input);
return view;
}
#Override
protected void onDialogClosed(boolean positiveResult) {
// When the user selects "OK", persist the new value
if (positiveResult) {
String sequenceValue = new String( sequenceInput.getText().toString() );
String[] parts = sequenceValue.split("-");
if(parts.length == 2) {
persistString(parts[1]);
}
}
}
}
I think this is a bug in Android API 18 and newer where extra whitespace is injected when a SharedPreferences string ends with \n. For more information, see:
https://code.google.com/p/android/issues/detail?id=159799#c6
https://code.google.com/p/android/issues/detail?id=159799#c7
after you retrieve the saved string, place a trim().
example
String sequence2 = sequence.trim()
All over the net I see examples like edittext.getText().toString(). I do not see any null check. In docs I do not see any statement that would say that this will never be null.
Still, what does the observations say; does this ever return null?
getText() will not return null. So there is no chance for NPE in following method. the getText will return empty string if there is no string, which is definitely not null
getText().toString();
However the edittext itself can be null if not initialized properly, Hence the following will trigger NPE
editText.getText().toString();
UPDATE:
It does appear as of Jan 18, 2018 this is now possible.
OLD ANSWER:
No, EditText.getText() never returns null. One way to verify this is to check the Android source code for EditText.getText():
EditText.java shows:
public Editable getText() {
return (Editable) super.getText();
}
Since EditText extends TextView, the call to super.getText() must be TextView.getText(). Now we move on to TextView.getText() to see what it returns:
TextView.java shows:
public CharSequence getText() {
return mText;
}
Now we need to know if mText could ever be null.
Digging deeper into the TextView.java source we see that mText is initialized as an empty string in the TextView constructor:
public TextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mText = "";
…
}
Once we see that the EditText constructor calls the TextView constructor:
public EditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
we can safely conclude that EditText.getText() can never return null, because as soon as an EditText is constructed, mText is given a value of an empty string.
However, as StinePike pointed out, EditText.getText() can possibly cause an NPE if your EditText is null when it makes the call to getText().
With Android P SDK it is annotated as nullable in the AppCompatEditText class so it can return null.
And from the docs:
Return the text that the view is displaying. If an editable text has not been set yet, this will return null.
#Override
#Nullable
public Editable getText() {
if (Build.VERSION.SDK_INT >= 28) {
return super.getText();
}
// A bug pre-P makes getText() crash if called before the first setText due to a cast, so
// retrieve the editable text.
return super.getEditableText();
}
I dont think so it will ever return null.
But if you want to check whether the returned text is empty or not might I suggest using TextUtils.isEmpty() method
Edit:- The documentation doesn't states anything regarding the returned value. And from what I've seen in the source code is that when you initialize a EditText, the default text value is set to "". So it will never return null
it will return null because when apps runs its empty and it returns null, use .getText.toString inside a button click listener, now when you click button it will get the text which you have entered on editText.
it is just because your edittext.getText().toString() is called directly in onCreate()...
This is why it return the initial value of editText.
You just have to create a function out of onCreate() and call it in event listener.
onCreate (){
….............
btn = (Button)findViewById(R.id.firstButton);
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
getValue ()
}
});
}
public void getValue () {
String editTextValue= edittext.getText().toString();
......
}
Or you Can call it directly in you onClickListenner in onCreate().
Like this:
onCreate (){
….............
btn = (Button)findViewById(R.id.firstButton);
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
String editTextValue= edittext.getText().toString();
.....
}
});
}
I Hope it will be helpful!
try in this way
String edittext = edittext.getText().toString();
if(edittext.length==0){ Log.d("null","the valueis null")};
I have a PreferenceScreen in which the user is capable, if system can't autodetect it, to enter the device's phone number. I'm still learning this part of Android but I managed to understand a bit of PreferenceScreens by examples provided by Android SDK itself and a few tutorials.
What I want is that the user can save the phone number only if null or valid, where by "valid" I mean running a generic validation logic (ie. an anonymous method that returns true or false, that can be reused in any possible situation*) or better, just to simplify things, ^(\+39)?3[0-9]{9}$
For now I have the following XML snip
<EditTextPreference
android:inputType="phone"
android:key="#string/preference_phoneNo"
android:selectAllOnFocus="true"
android:singleLine="true"
android:summary="#string/pref_phoneNumber_description"
android:title="#string/pref_phoneNumber" />
and following code by courtesy of Eclipse New Activity wizard:
private void setupSimplePreferencesScreen() {
if (!isSimplePreferences(this)) {
return;
}
addPreferencesFromResource(R.xml.pref_general);
bindPreferenceSummaryToValue(findPreference(getString(R.string.preference_phoneNo)));
}
addPreferenceFromResource is supposed to load the XML node and add the preference to the screen, while binPreferenceSummaryToValue is supposed to make description text change when preference is updated. Just for sake of completeness for those who don't like code courtesy of the IDE, the second method is provided by Eclipse who also provides a private class in the code file that is
/**
* A preference value change listener that updates the preference's summary
* to reflect its new value.
*/
In the general case, what should I do to perform validation logic before the preference gets saved when I click OK on the preference editor? Where is the validation logic to be put in a PreferenceScreen?
*Aren't we all here to learn?
Android has a built in helper method for this.
String phoneNumber = ...;
boolean valid = PhoneNumberUtils.isGlobalPhoneNumber(phoneNumber);
For a generic, re-usable method, here's the implementation of that method in PhoneNumberUtils, courtesy of AOSP (Apache licensed)
private static final Pattern GLOBAL_PHONE_NUMBER_PATTERN =
Pattern.compile("[\\+]?[0-9.-]+");
...
public static boolean isGlobalPhoneNumber(String phoneNumber) {
if (TextUtils.isEmpty(phoneNumber)) {
return false;
}
Matcher match = GLOBAL_PHONE_NUMBER_PATTERN.matcher(phoneNumber);
return match.matches();
}
Validation should occur within a Preference.OnPreferenceChangeListener , in the onPreferenceChange method. Simply return false if you don't want the value to be saved.
Example snippet:
private static Preference.OnPreferenceChangeListener myListener =
new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof PhoneNumberPreference) {
return isGlobalPhoneNumber(value);
}
}
...
As a note, since you're starting off with the Settings activity generated by the Eclipse wizard, this listener has already been built for you. You just need to edit it to include validation of the phone number (assuming that's what's being edited), and to return false if the number is invalid, so it won't be saved to preferences.
What I want to do is I am working on a game of life program. I want to take the time delay and make it a preference, but I want to make it available for people to type in a specific time. The number can be in miliseconds or seconds.
However I'm a little stuck on how to proceed, I haven't been able to find a simple preference that already handles this, but there might be one. Is there an easy way to make this preference and confirm that the entered data is an integer or afloat?
Use an EditTextPreference and set the input type to TYPE_CLASS_NUMBER. This will force the user to enter numbers and not letters.
EditTextPreference pref = (EditTextPreference)findPreference("preference_name");
pref.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
You can also enforce it with the xml attribute android:numeric. The possible relevant values for this attribute are decimal and integer.
You can also do this directly in your preferences.xml. Something like this would work:
<EditTextPreference
android:defaultValue="100"
android:dialogTitle="#string/pref_query_limit"
android:inputType="number"
android:key="pref_query_limit"
android:summary="#string/pref_query_limit_summ"
android:title="#string/pref_query_limit" />
If you are using a PreferenceActivity which you probably are, there is not one available.
You will need to do something like this:
/**
* Checks that a preference is a valid numerical value
*/
Preference.OnPreferenceChangeListener numberCheckListener = new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
//Check that the string is an integer.
return numberCheck(newValue);
}
};
private boolean numberCheck(Object newValue) {
if( !newValue.toString().equals("") && newValue.toString().matches("\\d*") ) {
return true;
}
else {
Toast.makeText(ActivityUserPreferences.this, newValue+" "+getResources().getString(R.string.is_an_invalid_number), Toast.LENGTH_SHORT).show();
return false;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//get XML preferences
addPreferencesFromResource(R.xml.user_preferences);
//get a handle on preferences that require validation
delayPreference = getPreferenceScreen().findPreference("pref_delay");
//Validate numbers only
delayPreference.setOnPreferenceChangeListener(numberCheckListener);
}
In Android Jetpack Preference things changed, to access EditText you have to access like this
val preference = findPreference<EditTextPreference>(getString(R.string.pref_numdefault_key))
preference?.setOnBindEditTextListener {
it.inputType = InputType.TYPE_CLASS_NUMBER
}
I need to do form input validation on a series of EditTexts. I'm using OnFocusChangeListeners to trigger the validation after the user types into each one, but this doesn't behave as desired for the last EditText.
If I click on the "Done" button while typing into the final EditText then the InputMethod is disconnected, but technically focus is never lost on the EditText (and so validation never occurs).
What's the best solution?
Should I be monitoring when the InputMethod unbinds from each EditText rather than when focus changes? If so, how?
Why don't you use TextWatcher ?
Since you have a number of EditText boxes to be validated, I think the following shall suit you :
Your activity implements android.text.TextWatcher interface
You add TextChanged listeners to you EditText boxes
txt1.addTextChangedListener(this);
txt2.addTextChangedListener(this);
txt3.addTextChangedListener(this);
Of the overridden methods, you could use the afterTextChanged(Editable s) method as follows
#Override
public void afterTextChanged(Editable s) {
// validation code goes here
}
The Editable s doesn't really help to find which EditText box's text is being changed. But you could directly check the contents of the EditText boxes like
String txt1String = txt1.getText().toString();
// Validate txt1String
in the same method. I hope I'm clear and if I am, it helps! :)
EDIT: For a cleaner approach refer to Christopher Perry's answer below.
TextWatcher is a bit verbose for my taste, so I made something a bit easier to swallow:
public abstract class TextValidator implements TextWatcher {
private final TextView textView;
public TextValidator(TextView textView) {
this.textView = textView;
}
public abstract void validate(TextView textView, String text);
#Override
final public void afterTextChanged(Editable s) {
String text = textView.getText().toString();
validate(textView, text);
}
#Override
final public void beforeTextChanged(CharSequence s, int start, int count, int after) { /* Don't care */ }
#Override
final public void onTextChanged(CharSequence s, int start, int before, int count) { /* Don't care */ }
}
Just use it like this:
editText.addTextChangedListener(new TextValidator(editText) {
#Override public void validate(TextView textView, String text) {
/* Validation code here */
}
});
If you want nice validation popups and images when an error occurs you can use the setError method of the EditText class as I describe here
In order to reduce the verbosity of the validation logic I have authored a library for Android. It takes care of most of the day to day validations using Annotations and built-in rules. There are constraints such as #TextRule, #NumberRule, #Required, #Regex, #Email, #IpAddress, #Password, etc.,
You can add these annotations to your UI widget references and perform validations. It also allows you to perform validations asynchronously which is ideal for situations such as checking for unique username from a remote server.
There is a example on the project home page on how to use annotations. You can also read the associated blog post where I have written sample codes on how to write custom rules for validations.
Here is a simple example that depicts the usage of the library.
#Required(order = 1)
#Email(order = 2)
private EditText emailEditText;
#Password(order = 3)
#TextRule(order = 4, minLength = 6, message = "Enter at least 6 characters.")
private EditText passwordEditText;
#ConfirmPassword(order = 5)
private EditText confirmPasswordEditText;
#Checked(order = 6, message = "You must agree to the terms.")
private CheckBox iAgreeCheckBox;
The library is extendable, you can write your own rules by extending the Rule class.
Updated approach - TextInputLayout:
Google has recently launched design support library and there is one component called TextInputLayout and it supports showing an error via setErrorEnabled(boolean) and setError(CharSequence).
How to use it?
Step 1: Wrap your EditText with TextInputLayout:
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/layoutUserName">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="hint"
android:id="#+id/editText1" />
</android.support.design.widget.TextInputLayout>
Step 2: Validate input
// validating input on a button click
public void btnValidateInputClick(View view) {
final TextInputLayout layoutUserName = (TextInputLayout) findViewById(R.id.layoutUserName);
String strUsername = layoutLastName.getEditText().getText().toString();
if(!TextUtils.isEmpty(strLastName)) {
Snackbar.make(view, strUsername, Snackbar.LENGTH_SHORT).show();
layoutUserName.setErrorEnabled(false);
} else {
layoutUserName.setError("Input required");
layoutUserName.setErrorEnabled(true);
}
}
I have created an example over my Github repository, checkout the example if you wish to!
This was nice solution from here
InputFilter filter= new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
String checkMe = String.valueOf(source.charAt(i));
Pattern pattern = Pattern.compile("[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789_]*");
Matcher matcher = pattern.matcher(checkMe);
boolean valid = matcher.matches();
if(!valid){
Log.d("", "invalid");
return "";
}
}
return null;
}
};
edit.setFilters(new InputFilter[]{filter});
I wrote a class that extends EditText which supports natively some validation methods and is actually very flexible.
Current, as I write, natively supported through xml attributes validation methods are:
alpha
alpha numeric
numeric
generic regexp
string emptyness
You can check it out here
Hope you enjoy it :)
I find InputFilter to be more appropriate to validate text inputs on android.
Here's a simple example:
How do I use InputFilter to limit characters in an EditText in Android?
You could add a Toast to feedback the user about your restrictions.
Also check the android:inputType tag out.
I needed to do intra-field validation and not inter-field validation to test that my values were unsigned floating point values in one case and signed floating point values in another. Here's what seems to work for me:
<EditText
android:id="#+id/x"
android:background="#android:drawable/editbox_background"
android:gravity="right"
android:inputType="numberSigned|numberDecimal"
/>
Note, you must not have any spaces inside "numberSigned|numberDecimal". For example: "numberSigned | numberDecimal" won't work. I'm not sure why.
This looks really promising and just what the doc ordered for me:
EditText Validator
public void onClickNext(View v) {
FormEditText[] allFields = { etFirstname, etLastname, etAddress, etZipcode, etCity };
boolean allValid = true;
for (FormEditText field: allFields) {
allValid = field.testValidity() && allValid;
}
if (allValid) {
// YAY
} else {
// EditText are going to appear with an exclamation mark and an explicative message.
}
}
custom validators plus these built in:
regexp: for custom regexp
numeric: for an only numeric field
alpha: for an alpha only field
alphaNumeric: guess what?
personName: checks if the entered text is a person first or last name.
personFullName: checks if the entered value is a complete full name.
email: checks that the field is a valid email
creditCard: checks that the field contains a valid credit card using Luhn Algorithm
phone: checks that the field contains a valid phone number
domainName: checks that field contains a valid domain name ( always passes the test in API Level < 8 )
ipAddress: checks that the field contains a valid ip address
webUrl: checks that the field contains a valid url ( always passes the test in API Level < 8 )
date: checks that the field is a valid date/datetime format ( if customFormat is set, checks with customFormat )
nocheck: It does not check anything except the emptyness of the field.
In main.xml file
You can put the following attrubute to validate only alphabatics character can accept in edittext.
Do this :
android:entries="abcdefghijklmnopqrstuvwxyz"
You can get desired behavior by listening when user hit "Done" button on keyboard, also checkout other tips about working with EditText in my post "Android form validation - the right way"
Sample code:
mTextView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
validateAndSubmit();
return true;
}
return false;
}});
for email and password validation try
if (isValidEmail(et_regemail.getText().toString())&&etpass1.getText().toString().length()>7){
if (validatePassword(etpass1.getText().toString())) {
Toast.makeText(getApplicationContext(),"Go Ahead".....
}
else{
Toast.makeText(getApplicationContext(),"InvalidPassword".....
}
}else{
Toast.makeText(getApplicationContext(),"Invalid Email".....
}
public boolean validatePassword(final String password){
Pattern pattern;
Matcher matcher;
final String PASSWORD_PATTERN = "^(?=.*[0-9])(?=.*[A-Z])(?=.*
[##$%^&+=!])(?=\\S+$).{4,}$";
pattern = Pattern.compile(PASSWORD_PATTERN);
matcher = pattern.matcher(password);
return matcher.matches();
}
public final static boolean isValidEmail(CharSequence target) {
if (target == null)
return false;
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
I have created this library for android where you can validate a material design EditText inside and EditTextLayout easily like this:
compile 'com.github.TeleClinic:SmartEditText:0.1.0'
then you can use it like this:
<com.teleclinic.kabdo.smartmaterialedittext.CustomViews.SmartEditText
android:id="#+id/passwordSmartEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:setLabel="Password"
app:setMandatoryErrorMsg="Mandatory field"
app:setPasswordField="true"
app:setRegexErrorMsg="Weak password"
app:setRegexType="MEDIUM_PASSWORD_VALIDATION" />
<com.teleclinic.kabdo.smartmaterialedittext.CustomViews.SmartEditText
android:id="#+id/ageSmartEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:setLabel="Age"
app:setMandatoryErrorMsg="Mandatory field"
app:setRegexErrorMsg="Is that really your age :D?"
app:setRegexString=".*\\d.*" />
Then you can check if it is valid like this:
ageSmartEditText.check()
For more examples and customization check the repository
https://github.com/TeleClinic/SmartEditText