Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change text edit error notification font in android

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?

like image 397
hamidfzm Avatar asked May 01 '14 21:05

hamidfzm


2 Answers

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);
    }
}
like image 160
myanimal Avatar answered Sep 30 '22 05:09

myanimal


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>"));
like image 35
canova Avatar answered Sep 30 '22 06:09

canova