我想将两种不同的字体样式应用于单个 TextView 中的文本。
我的情况与Android - 两句话,两种样式,一个TextView https://stackoverflow.com/questions/8999781/android-two-sentences-two-styles-one-textview。唯一的区别是我想在整个文本上设置自定义字体。我已将 Helvetica 字体作为资产包含在我的项目中,并希望将该字体应用于 TextView,文本的第一部分将是 Helvetica BOLD,其余部分将是 Helvetica NORMAL。有什么建议可以如何做到吗?
需要以下格式的文本。具有不同样式和单个文本视图的自定义文本。
做到这一点的一种方法是扩展字体跨度 https://stackoverflow.com/questions/4819049/how-can-i-use-typefacespan-or-stylespan-with-custom-typeface:
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);
}
}
然后,当您想使用两种不同的字体时,请调用:
String firstWord = "first ";
String secondWord = "second";
// Create a new spannable with the two strings
Spannable spannable = new SpannableString(firstWord+secondWord);
// Set the custom typeface to span over a section of the spannable object
spannable.setSpan( new CustomTypefaceSpan("sans-serif",CUSTOM_TYPEFACE), 0, firstWord.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan( new CustomTypefaceSpan("sans-serif",SECOND_CUSTOM_TYPEFACE), firstWord.length(), firstWord.length() + secondWord.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// Set the text of a textView with the spannable object
textView.setText( spannable );
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)