创建一个 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 的答案有共同的缺陷。跨度没有被分割。即如果你这样做(kotlin):
val parcel = Parcel.obtain()
TextUtils.writeToParcel(spannableStringBuilder, parcel, 0)
parcel.setDataPosition(0)
val sequence = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(parcel)
parcel.recycle()
设置的任何CustomTypefaceSpan
对象spannableStringBuilder
都不会被编组和解组。