我有一个TextView,我需要在其上显示以下字符串:"一些文本"。我希望TextView为此使用自定义字体。所以我需要得到以下输出:
我尝试了以下代码:
textView.setText("some <i>text</i>");
final Typeface typeface = Typeface.createFromAsset(getActivity().getAssets(), "customfont-regular.otf");
if (typeface != null)
textView.setTypeface(typeface);
但结果是:,所以Italic实际上是假的,由系统生成。然后我尝试了以下内容:
textView.setText("some <i>text</i>");
final Typeface typeface = Typeface.createFromAsset(getActivity().getAssets(), "customfont-regular.otf");
if (typeface != null)
textView.setTypeface(typeface, Typeface.NORMAL);
final Typeface typefaceItalic = Typeface.createFromAsset(getActivity().getAssets(), "customfont-italic.otf");
if (typefaceItalic != null)
textView.setTypeface(typefaceItalic, Typeface.ITALIC);
但输出是全部的!
那么如何在单个TextView中组合常规和斜体的自定义字体?
答案 0 :(得分:0)
经过一番研究后,我找到了以下解决方案:
final Typeface typefaceItalic = Typeface.createFromAsset(getActivity().getAssets(), "customfont-italic.otf");
// there is no easy way in Android to make a single TextView display text using custom typeface with different styles (regular and italic). We need to replace all Italic spans with custom typeface spans for this.
final SpannableString text = new SpannableString("some <i>text</i>");
final StyleSpan[] spans = text.getSpans(0, text.length(), StyleSpan.class);
for (StyleSpan span : spans) {
if (span.getStyle() == Typeface.ITALIC) {
text.setSpan(new CustomTypefaceSpan("customfont", italicTypeface), text.getSpanStart(span), text.getSpanEnd(span), 0);
text.removeSpan(span);
}
}
textView.setText(text);
final Typeface typeface = Typeface.createFromAsset(getActivity().getAssets(), "customfont-regular.otf");
if (typeface != null)
textView.setTypeface(typeface, Typeface.NORMAL);
CustomTypefaceSpan
是此处描述的类:https://stackoverflow.com/a/4826885/190148