gpt4 book ai didi

android - 使 TextView 使用具有不同样式(常规和斜体)的自定义字体

转载 作者:行者123 更新时间:2023-11-28 03:19:34 24 4
gpt4 key购买 nike

我有一个 TextView,我需要在上面显示以下字符串:“Some text”。我希望 TextView 为此使用自定义字体。所以我需要得到以下输出:enter image description here

我尝试了以下代码:

    textView.setText("some <i>text</i>");
final Typeface typeface = Typeface.createFromAsset(getActivity().getAssets(), "customfont-regular.otf");
if (typeface != null)
textView.setTypeface(typeface);

但结果是:enter image description here ,所以斜体实际上是假的,由系统生成。然后我尝试了以下操作:

    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);

但是输出全是斜体! enter image description here

那么如何在单个 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

关于android - 使 TextView 使用具有不同样式(常规和斜体)的自定义字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25264864/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com