如何使用自定义字体设置Spannable对象字体

moh*_*emi 63 android android-fonts spannable

我有Spannable对象,我想通过我之前加载的自定义字体设置其字体.

Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/font_Name.ttf");
Spannable span1 = /*Spannable Item*/;

/// I want to set span1 to have tf font face???
/// Here where I want help.
Run Code Online (Sandbox Code Playgroud)

编辑:
我的问题是我想为文本视图设置两种不同的自定义字体,所以我正在使用Spannable

Imr*_*ana 194

这是一个迟到的答案,但将帮助其他人解决问题.

使用以下代码:(我使用的是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);
Run Code Online (Sandbox Code Playgroud)

结果是:

在此输入图像描述


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);
}
}
Run Code Online (Sandbox Code Playgroud)

参考

  • 不错的 - 虽然如果你要与家人一起使用它"",为什么不完全从构造函数中删除family参数,只需调用super(""); (9认同)

ale*_*ett 16

创建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);
    }
}
Run Code Online (Sandbox Code Playgroud)

使用方式与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);
Run Code Online (Sandbox Code Playgroud)

这个答案基于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()
Run Code Online (Sandbox Code Playgroud)

CustomTypefaceSpan设置的任何对象spannableStringBuilder都不会被编组和解组.


小智 13

我们不需要使用CustomTypefaceSpan.这是解决方案.

/**
* setCustomFontTypeSpan
* @param context
* @param source
* @param startIndex
* @param endIndex
* @param font
* @return
*/
public static SpannableString setCustomFontTypeSpan(Context context, String 
source, int startIndex, int endIndex, int font) {
      final SpannableString spannableString = new SpannableString(source);
      Typeface typeface = ResourcesCompat.getFont(context, font);
      spannableString.setSpan(new StyleSpan(typeface.getStyle()), 
      startIndex,endIndex,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannableString;
}

String source = "Hello world";
SpannableString string = setCustomFontTypeSpan(context, source, 6, 
source.length(), R.font.open_sans_bold);
textView.setText(string);
Run Code Online (Sandbox Code Playgroud)

  • StyleSpan 无意设置 typeFace。如文档中所述:跨度允许设置其附加文本的样式。可能的样式有:Typeface#NORMAL、Typeface#BOLD、Typeface#ITALIC 和 Typeface#BOLD_ITALIC。给定的代码会将span设置为BOLD,不影响字体 (4认同)

MJ *_*dio 12

如果您使用的是 Android KTX buildSpannable{...}

我推荐这个。

inline fun SpannableStringBuilder.font(typeface: Typeface? = null, builderAction: SpannableStringBuilder.() -> Unit) =
    inSpans(StyleSpan(typeface?.style ?: Typeface.DEFAULT.style), builderAction = builderAction)
Run Code Online (Sandbox Code Playgroud)

用法

binding.title.text = buildSpannedString {
    color(getColor(R.color.main_mint)) {
        font(getFont(R.font.notosans_medium)) {
            append("colored and typefaced")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Ren*_*ery 10

如果您使用的是Roboto,则可以在构造函数中设置不同的TypefaceSpan

__CODE__

__CODE__


Tar*_*rik 6

我想做同样的事情,但我发现我需要使用 TypefaceSpan。问题是采用 Typeface 的构造函数仅在 API 级别 28 中添加。因此我发现的解决方法是执行以下操作:

val spannable = SpannableString("My String")
spannable.setSpan(object : TypefaceSpan(null) {
    override fun updateDrawState(ds: TextPaint) {
        ds.typeface = Typeface.create(ResourcesCompat.getFont(context, R.font.my_font), Typeface.NORMAL) // To change according to your need
    }
}, start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE) // To change according to your need
myTextView.setText(spannable)
Run Code Online (Sandbox Code Playgroud)


pet*_*o16 5

在 kotlin 中是:

第一步,创建这个类

class CustomTypefaceSpan(family: String?, private val newType: Typeface) :
  TypefaceSpan(family) {
  override fun updateDrawState(ds: TextPaint) {
      applyCustomTypeFace(ds, newType)
  }

  override fun updateMeasureState(paint: TextPaint) {
      applyCustomTypeFace(paint, newType)
  }

  companion object {
      private fun applyCustomTypeFace(paint: Paint, tf: Typeface) {
          val oldStyle: Int
          val old = paint.typeface
          oldStyle = old?.style ?: 0
          val fake = oldStyle and tf.style.inv()
          if (fake and Typeface.BOLD != 0) {
              paint.isFakeBoldText = true
          }
          if (fake and Typeface.ITALIC != 0) {
              paint.textSkewX = -0.25f
          }
          paint.typeface = tf
      }
  }

}
Run Code Online (Sandbox Code Playgroud)

第二步

    val prefixText = SpannableString("I read and accept ")
    val prefixTextLen = prefixText.length

    prefixText.setSpan(
        CustomTypefaceSpan("", ResourcesCompat.getFont(context, R.font.gotham_bold)!!),
        0,
        prefixTextLen,
        0
    )
Run Code Online (Sandbox Code Playgroud)


Sha*_*ert 5

>= API 28 的更新、更简单的答案

val myTypeface = Typeface.create(ResourcesCompat.getFont(context, R.font.acme), Typeface.NORMAL)
val string = SpannableString("Text with typeface span.")
string.setSpan(TypefaceSpan(myTypeface), 10, 18, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
string.setSpan(TypefaceSpan("monospace"), 19, 22, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

textView.text = string
Run Code Online (Sandbox Code Playgroud)