Question

I know we can change edit text font by using Typeface. But what about errors we set for edit text? Look at codes below:

Typeface font = Typeface.createFromAsset(getAssets(), "fonts/ATaha.ttf");
private EditText mPasswordView;
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setTypeface(font);

With this code I could only change edit text font but when I set error like this:

mPasswordView.setError(getString(R.string.error_field_required));

The error notification font is android default font and didn't change by using type face. How can I change that?

Was it helpful?

Solution

You can use a SpannableString to set the font:

SpannableString s = new SpannableString(errorString);
s.setSpan(new TypefaceSpan(font), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
mPasswordView.setError(s);

A custom Span class that has a specific Typeface set:

public class TypefaceSpan extends MetricAffectingSpan {
    private Typeface mTypeface;
    public TypefaceSpan(Typeface typeface) {
        mTypeface = typeface;
    }

    @Override
    public void updateMeasureState(TextPaint p) {
        p.setTypeface(mTypeface);
        p.setFlags(p.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
    }

    @Override
    public void updateDrawState(TextPaint tp) {
        tp.setTypeface(mTypeface);
        tp.setFlags(tp.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
    }
}

OTHER TIPS

Since you can't directly set a Typeface for error text, you can achieve it by setting an HTML string as a text inside it.

You can see HTML Tags supported by a TextView in The CommonsBlog

We have face attribute for font, which means you can change the font-family.

mPasswordView.setError(Html.fromHtml("<font face='MONOSPACE'>Error font is MONOSPACE</font>"));

By setting spannable string in error message or extend EditText and overrite your own error draw mechanism.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top