java 单个 TextView 中的多个字体

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10675070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 02:02:51  来源:igfitidea点击:

Multiple TypeFace in single TextView

javaandroid

提问by JustMe

I want to set the first character on TextViewwith a TypeFaceand the second character with a different Type face and so on.
I read this example:

我想TextView用 a设置第一个字符,用TypeFace不同的 Type face 设置第二个字符,依此类推。
我读了这个例子:

Spannable str = (Spannable) textView.getText();
str.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, 7  
                             ,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

but it didn't help me, because I want to set multiple TypeFace (external TTFs)
Any idea??

但这对我没有帮助,因为我想设置多个TypeFace (external TTFs)
任何想法?

回答by Imran Rana

Use the following code:(I'm using Bangla and Tamil font)

使用以下代码:(我使用的是孟加拉语和泰米尔语字体)

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


The outcome is:

结果是:

enter image description here

在此处输入图片说明



This uses the CustomTypefaceSpanclass, taken from How can I use TypefaceSpan or StyleSpan with a custom Typeface?:

这使用了CustomTypefaceSpan类,取自如何将 TypefaceSpan 或 StyleSpan 与自定义字体一起使用?



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