Christina
Christina

Reputation: 129

Change EditText.setError() background and error message android

I want to change the text and background color of error message for invalid email address. I tried but my text message doesn't display any content. here is my code.

public class TextboxValidation {


    //validating email address

    public static boolean validateEditText(EditText editText) {
        boolean valid = true;
        Context context;

        String text = editText.getText().toString();

        boolean isEmail = (editText.getInputType() & InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS) == InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS;
        boolean isNumeric = (editText.getInputType() & InputType.TYPE_NUMBER_FLAG_DECIMAL) == InputType.TYPE_NUMBER_FLAG_DECIMAL;

        if (TextUtils.isEmpty(text)) {
            if (!isNumeric || !TextUtils.isDigitsOnly(editText.getHint())) {
                valid = false;
            }

        } else if (isEmail) {
            valid = android.util.Patterns.EMAIL_ADDRESS.matcher(text).matches();
        }

        if (!valid) {
            context = editText.getContext();

            if (isEmail) {

                int ecolor = R.color.black; // whatever color you want
                String estring = "Veuillez saisir une addresse email valide";
                ForegroundColorSpan fgcspan = new ForegroundColorSpan(ecolor);
                SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
                ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);

                editText.setError(ssbuilder);
            } else {
                editText.setError("Le champ ne peut etre vide.");
            }
            return false;
        }

        editText.setError(null);
        return true;
    }
}

Upvotes: 2

Views: 9450

Answers (2)

vss
vss

Reputation: 1153

You can do like this.

if (TextUtils.isEmpty(cashierid)) {
        cid.setError(Html.fromHtml("<font color='red'>Username can't be empty</font>"));
        return;
    }
else if (TextUtils.isEmpty(cashierpwd)) {
        cpwd.setError(Html.fromHtml("<font color='red'>Password can't be empty</font>"));
        return;
    }

Upvotes: 0

Pradeep
Pradeep

Reputation: 104

You can change the text color by using HTML Font Tag.

But for customizing background color, you should make your own custom pop up. For more information, Kindly go through this link:- How to write style to error text of EditText in android?

Upvotes: 0

Related Questions