【问题标题】:Change text edit error notification font in android在android中更改文本编辑错误通知字体
【发布时间】:2014-05-01 21:30:06
【问题描述】:

我知道我们可以使用Typeface 更改编辑文本字体。但是我们为编辑文本设置的错误呢? 看下面的代码:

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

使用此代码,我只能更改编辑文本字体,但是当我设置如下错误时:

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

错误提示字体为android默认字体,没有因使用字体而改变。我该如何改变呢?

【问题讨论】:

标签: android android-edittext typeface


【解决方案1】:

您可以使用SpannableString 来设置字体:

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

具有特定 Typeface 集的自定义 Span 类:

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

【讨论】:

  • 它适用于我在 Android 4.4 上,但应该适用于所有版本。你能发布你的代码来设置这样的错误吗?
  • 哦,等等,我忘了我正在使用自定义 TypefaceSpan 类。我现在会更新我的答案..
  • 它工作得非常好,但有什么方法可以在不使用新对象和创建新对象的情况下更改SpannableString
  • 我想不到,抱歉。开销不应该太多,除非你有一个包含 1000 个EditTexts 的表单,这太疯狂了。
【解决方案2】:

由于不能直接为错误文本设置Typeface,因此可以通过在其中设置一个HTML字符串作为文本来实现。

你可以在The CommonsBlog中看到TextView支持的HTML标签

我们有face 字体属性,这意味着您可以更改字体系列。

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

【讨论】:

  • asserts 文件夹中的自定义字体怎么样?我需要使用自定义字体。
【解决方案3】:

通过在错误消息中设置可扩展字符串或扩展 EditText 并覆盖您自己的错误绘制机制。

【讨论】:

    猜你喜欢
    • 2019-02-25
    • 2020-12-30
    • 2019-11-30
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    • 2012-03-10
    相关资源
    最近更新 更多