更改EditText.setError()背景和错误消息android

时间:2013-04-23 10:02:04

标签: android android-edittext

我想更改无效电子邮件地址的错误消息的文本和背景颜色。我试过,但我的短信没有显示任何内容。这是我的代码。

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;
    }
}

2 个答案:

答案 0 :(得分:0)

您可以使用 HTML字体标记

更改文字颜色

但是要自定义背景颜色,您应该自定义弹出窗口。 欲了解更多信息,请通过以下链接: - How to write style to error text of EditText in android?

答案 1 :(得分:0)

你可以这样做。

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;
    }