android - 如何将字体样式添加到TextView Android Kotlin

标签 android html kotlin fromhtml

我需要帮助,我陷入了困境。我的要求是,我需要在工具提示中添加文本。我实际上是这样做的。但是文本包括多行文本,还有一些具有粗体样式的行,其他具有常规样式和自定义字体样式的行。通过下面的代码,我可以添加粗体,斜体和常规样式。但是我需要在文本中添加以下自定义字体样式。请看看我下面的代码。

textViewToShow.setOnClickListener { view ->

    val tfBold = Typeface.createFromAsset(
        context!!.assets,
        "fonts/myriad_pro_bold.ttf"
    )

    val tfRegular = Typeface.createFromAsset(
        context!!.assets,
        "fonts/myriad_pro_regular.ttf"
    )

    var string1 = “Item show in Bold style”
    var string2 = “Item show in Regular style”
    var string3 = “Item show in Regular style with item description”

    val holesTextView = Html.fromHtml("<b>" + string1 + "</b> <br><br> <b><i>"+ string2 + "</i></b> " + string3)
    showToolTip(view, holesTextView)

}

    private fun showToolTip(view: View, holesTextView: Spanned) {
        val builder: Tooltip.Builder =
            Tooltip.Builder(view, R.style.Tooltip)
                .setText(holesTextView)
        builder.show()
    }


任何解决方案/建议都受到高度赞赏

最佳答案

我会创建一个font family

<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
    <font
        android:fontStyle="normal"
        android:fontWeight="400"
        android:font="@font/myriad_pro_regular" />
    <font
        android:fontStyle="italic"
        android:fontWeight="400"
        android:font="@font/myriad_pro_italic" />
    <font
        android:fontStyle="normal"
        android:fontWeight="700"
        android:font="@font/myriad_pro_bold" />
</font-family>

遵循How to create custom font family with bold font的粗体字答案。

然后,您可以在布局中分配字体系列:
<EditText
    android:fontFamily="@font/mycustomfont"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Hello, World!" />

或以编程方式:
val typeface = ResourcesCompat.getFont(context, R.font.mycustomfont)
holesTextView.setTypeface(typeface)

如果是tooltip,则使用其setTypeface()方法:
val typeface = ResourcesCompat.getFont(context, R.font.mycustomfont)
val builder: Tooltip.Builder = Tooltip.Builder(view, R.style.Tooltip)
    .setText(holesTextView)
    .setTypeface(typeface)
    builder.show()

并使用HtmlCompat.fromHtml,因为不推荐使用Html.fromHtml:
val holesTextView = HtmlCompat.fromHtml("<b>" + string1 + "</b> <br><br> <b><i>"+ string2 + "</i></b> " + string3, HtmlCompat.FROM_HTML_MODE_LEGACY)

关于android - 如何将字体样式添加到TextView Android Kotlin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61608293/

相关文章:

javascript - HTML 4.01 验证双引号问题

android - Kotlin Coroutines - 从 Coroutine 返回一个值而不阻塞主线程 Android

android - 如何在使用 PointerInput 修改器时添加点击时的波纹效果

android - 输入类型无法正常工作

html - 如何使用 CodeIgniter 引用我的 Bootstrap 样式表

javascript - 打印包含动态图像的 div

gradle - Intellij IDEA在项目向导中没有Kotlin Native

android - 如何在 AsyncTask 中调用 Activity 方法

android - 如何回到 fragment 的前一个 Root View

android - 集成 tabhost 和抽屉导航