android - 对具有 HTL 格式的相同 TextView 使用不同的字体

标签 android html typeface

我已经知道如何为我的 TextView 指定自定义字体。截至目前,我的应用程序使用一种自定义字体,该字体分为两个 ttf 文件。一个用于常规字符,一个用于粗体字符。

现在,我希望能够像使用 Html.fromHtml() 一样使用一个 TextView。由于它适用于系统字体,因此它应该能够使用我自己的字体来完成。目前,粗体字符是用常规字体和假粗体文本绘制的,非常难看。

有什么想法吗?

谢谢

最佳答案

如果您想在单个 TextView 中使用多种自定义字体:

使用以下代码:(我使用的是 Bangla 和 Tamil 字体)

  TextView txt = (TextView) findViewById(R.id.custom_fonts);  
        txt.setTextSize(30);
        Typeface font = Typeface.createFromAsset(getAssets(), "Akshar.ttf");
        Typeface font2 = Typeface.createFromAsset(getAssets(), "bangla.ttf");   
        SpannableStringBuilder SS = new SpannableStringBuilder("আমারநல்வரவு");
        SS.setSpan (new CustomTypefaceSpan("", font2), 0, 4,Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        SS.setSpan (new CustomTypefaceSpan("", font), 4, 11,Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        txt.setText(SS);

结果是:

enter image description here


CustomTypefaceSpan 类:

package my.app;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.text.style.TypefaceSpan;

public class CustomTypefaceSpan extends TypefaceSpan {

private final Typeface newType;

public CustomTypefaceSpan(String family, Typeface type) {
    super(family);
    newType = type;
}

@Override
public void updateDrawState(TextPaint ds) {
    applyCustomTypeFace(ds, newType);
}

@Override
public void updateMeasureState(TextPaint paint) {
    applyCustomTypeFace(paint, newType);
}

private static void applyCustomTypeFace(Paint paint, Typeface tf) {
    int oldStyle;
    Typeface old = paint.getTypeface();
    if (old == null) {
        oldStyle = 0;
    } else {
        oldStyle = old.getStyle();
    }

    int fake = oldStyle & ~tf.getStyle();
    if ((fake & Typeface.BOLD) != 0) {
        paint.setFakeBoldText(true);
    }

    if ((fake & Typeface.ITALIC) != 0) {
        paint.setTextSkewX(-0.25f);
    }

    paint.setTypeface(tf);
}
}

Reference

关于android - 对具有 HTL 格式的相同 TextView 使用不同的字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10888363/

相关文章:

Android - 如何更改底部导航栏文本的字体系列

android - 我的 Android 小部件被杀死, "No longer want bellander.andro...."

html - 图像不与文本保持内联

android - 使用 SimpleAdapter 在 Android ListView 中自定义字体

javascript - <img>重载时宽度返回0

html - CSS 中多少个逗号算过多逗号

java - 如何更改上下文操作栏的字体?

java - 动态(以编程方式)创建 View 时, View 在卡片 View 中重叠

android - Quickblox:与离线用户进行视频通话的策略是什么

java - 在 AsyncTask 上使用 filesDir (Kotlin)