riz*_*z86 28 fonts android styles textview
我想将两种不同的字体样式应用于单个TextView中的文本.
我的情况与Android相同- 两个句子,两个样式,一个TextView.唯一的区别是我想在整个文本上设置自定义字体.我已将Helvetica Font作为资产包含在我的项目中,并希望将该字体应用于TextView,文本的第一部分将是Helvetica BOLD,其余部分为Helvetica NORMAL.有什么建议怎么办?
需要以下格式的文字.具有不同样式和单个textview的自定义文本.

Ljd*_*son 76
一种方法是扩展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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后当你想使用两种不同的字体时调用:
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 );
Run Code Online (Sandbox Code Playgroud)
这是一个更直接的解决方案,您可以使用 HTML 在同一个TextView.
例如:
// Styled label
String styledText = "<big><b><font color='#333333'>title</font></b></big> <small><b><font color='#CC5490'>subtitle</font></b></small>";
// Apply the styled label on the TextView
textView.setText(Html.fromHtml(styledText));
Run Code Online (Sandbox Code Playgroud)
您需要以下导入:
import android.text.Html;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28510 次 |
| 最近记录: |