我有一个TextView,我需要在其上显示以下字符串:“ Some text ”。我希望TextView为此使用自定义字体。所以我需要获得以下输出:
我尝试了以下代码:
textView.setText("some <i>text</i>");
final Typeface typeface = Typeface.createFromAsset(getActivity().getAssets(), "customfont-regular.otf");
if (typeface != null)
textView.setTypeface(typeface);
但是结果是:,因此斜体实际上是假的,由系统生成。然后我尝试了以下方法:
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中结合常规和斜体的自定义字体?
经过研究,我找到了以下解决方案:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句