创建一个CustomTypefaceSpan类:
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.text.style.MetricAffectingSpan;
public class CustomTypefaceSpan extends MetricAffectingSpan {
private final Typeface typeface;
public CustomTypefaceSpan(Typeface typeface) {
this.typeface = typeface;
}
@Override
public void updateDrawState(TextPaint ds) {
applyCustomTypeFace(ds, typeface);
}
@Override
public void updateMeasureState(TextPaint paint) {
applyCustomTypeFace(paint, typeface);
}
private static void applyCustomTypeFace(Paint paint, Typeface tf) {
paint.setTypeface(tf);
}
}
使用与Android框架跨度类相同的方式:
TextView textView = (TextView) findViewById(R.id.custom_fonts);
Typeface font = Typeface.createFromAsset(getAssets(), "Akshar.ttf");
Typeface font2 = Typeface.createFromAsset(getAssets(), "bangla.ttf");
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder("আমারநல்வரவு");
spannableStringBuilder.setSpan (new CustomTypefaceSpan(font2), 0, 4,Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
spannableStringBuilder.setSpan (new CustomTypefaceSpan(font), 4, 11,Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
textView.setText(spannableStringBuilder);
这个答案基于Imran Rana的回答,但不扩展TypefaceSpan
并禁用其功能。 CustomTypefaceSpan
直接扩展了MetricAffectingSpan
。
这个答案与Imran Rana的回答一样存在缺陷。该span未被打包,也就是说,如果您执行以下操作(kotlin):
val parcel = Parcel.obtain()
TextUtils.writeToParcel(spannableStringBuilder, parcel, 0)
parcel.setDataPosition(0)
val sequence = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(parcel)
parcel.recycle()
在SpannableStringBuilder
上设置的任何CustomTypefaceSpan
对象都不会被编组和解组。