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);
この回答はImranRanaの回答に基づいていますが、拡張TypefaceSpan
してその機能を無効にすることはありません。CustomTypefaceSpan
直接伸びMetricAffectingSpan
ます。
この回答は、ImranRanaの回答と欠陥を共有しています。スパンはパーセルされていません。つまり、これを行う場合(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
およびアンマーシャリングされません。