问题描述
我要申请两个不同的字体样式到一个文本在一个TextView中。
I want to apply two different font styles to a text in a single TextView.
我的情况是一样的Android - 两句话,两种风格,一是TextView的。唯一的区别是,我想对整个文本设置自定义字体。我已经包括Helvetica字体作为我的项目的资产,并希望该字体应用到与文本的第一部分的TextView将黑体大胆及剩余部分黑体师范大学。任何建议如何可以做到?
My case is same as Android - two sentences, two styles, one TextView. The only difference is that I want to set a Custom Font on the whole text. I have included Helvetica Font as an assets in my project and want to apply that font to the TextView with first part of the text will be Helvetica BOLD and remaining part Helvetica NORMAL. Any suggestions how it can be done ?
需要下面的格式文本。自定义文本不同的风格和单一的TextView。
Text needed in following format. Custom text with different styles and single textview.
推荐答案
要做到这一点的方法之一是扩大TypefaceSpan:
One way to do this is to extend TypefaceSpan:
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);
}
}
然后,当你要使用两个不同的字体拨打:
Then when you want to use two different typefaces call:
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 );
这篇关于适用两种不同的字体样式到一个TextView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!