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

标签 android html textview typeface

我有一个 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/

相关文章:

android - 根访问副作用

javascript - 如何使用<audio>标签html5再现声音序列

html - 又一个 HTML/CSS 布局挑战——带有粘性页脚的全高侧边栏

安卓 : Clickable link of sdcard storage

android - 添加安卓 :id to xml breaks entire app

java.lang.NullPointerException : Attempt to invoke virtual method 'int android.view.ViewGroup.getPaddingLeft()' on a null object reference 异常

php - 在php和Mysql中更新数据

java - 在我的 MainActivity 的 textView 中设置文本

android - 在 Android TextView 中显示进度

android - 如何从字符串数组填充 Spinner