前言:安卓系统默认的字体在显示文字时,如果文字内容中有中文符号,比如中文的双引号“”,会显示的不够醒目,如图1:
如果想将这些符号用更加醒目的字体比如“宋体”来显示,如图2:
对于安卓Q及其以上系统,直接使用原生的类即可。
而对于5.0(21 sdk)等低版本系统,就得自己想办法写代码来“曲线救国”了。
方法如下:
1. 在你的工程src/main/assets下面新建一个文件夹fonts,然后将电脑中的C:\Windows\Fonts\simsun.ttc拷贝到fonts下面。
2. 附上代码 :
import android.text.TextPaint;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.TypefaceSpan;
import android.graphics.Paint;
import android.graphics.Typeface;// 添加自定义TypefaceSpan类来正确处理自定义字体private static class CustomTypefaceSpan extends TypefaceSpan {private final Typeface newType;public CustomTypefaceSpan(Typeface type) {super("");newType = type;}@Overridepublic void updateDrawState(TextPaint ds) {applyCustomTypeFace(ds, newType);}@Overridepublic 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);}}private void showSongTiText(TextView tv, String text) {runOnUiThread(() -> {if (text == null) {tv.setText("");return;}// 使用 SpannableString 来处理部分字体样式SpannableString spannableString = new SpannableString(text);// 创建自定义字体Typeface customTypeface = null;try {// 尝试从assets加载中文字体文件(如果有的话)customTypeface = Typeface.createFromAsset(getAssets(), "fonts/simsun.ttc");} catch (Exception e) {LogUtil.error(TAG, "字体加载失败:" + e.getMessage());// 回退到系统serif字体customTypeface = Typeface.create(Typeface.SERIF, Typeface.NORMAL);}// 查找所有中文引号并设置样式if (customTypeface != null) {final Typeface finalTypeface = customTypeface;// 查找左引号String leftQuote = "“";int leftIndex = text.indexOf(leftQuote);while (leftIndex != -1) {// 为左引号设置样式spannableString.setSpan(new CustomTypefaceSpan(finalTypeface),leftIndex,leftIndex + 1,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);// 继续查找下一个左引号leftIndex = text.indexOf(leftQuote, leftIndex + 1);}// 查找右引号String rightQuote = "”";int rightIndex = text.indexOf(rightQuote);while (rightIndex != -1) {// 为右引号设置样式spannableString.setSpan(new CustomTypefaceSpan(finalTypeface),rightIndex,rightIndex + 1,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);// 继续查找下一个右引号rightIndex = text.indexOf(rightQuote, rightIndex + 1);}}// tv.setText(text);tv.setText(spannableString);});}
注:以上代码可能有未导入的类,你直接Alt+Enter导入一下即可。