android 将字体设置为TextView将删除字体并将其设置为默认字体

eit6fx6z  于 2022-11-20  发布在  Android
关注(0)|答案(1)|浏览(256)

我通过设置typeface = Typeface.DEFAULT_BOLD使文本加粗。它起作用了,但是我的字体(Monserrat)变成了默认字体(Roboto)。我怎样才能在不影响字体的情况下更改加粗呢?
设置字体的功能:

fun setTabTypeface(tab: TabLayout.Tab, typeface: Typeface?) {
    for (i in 0 until tab.view.childCount) {
        val tabViewChild: View = tab.view.getChildAt(i)
        if (tabViewChild is TextView) tabViewChild.typeface = typeface
    }
}

我怎么称呼它:

fun TabLayout.onTabSelectedListener(
    onFollowClickListener: ((String) -> Unit),
) {
    this.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
        override fun onTabSelected(tab: TabLayout.Tab) {
            setTabTypeface(tab, Typeface.DEFAULT_BOLD)
        }

        override fun onTabUnselected(tab: TabLayout.Tab?) {
            tab?.let { setTabTypeface(tab, Typeface.DEFAULT) }
        }

        override fun onTabReselected(tab: TabLayout.Tab?) {
        }
    })
}

我仅在此处指定字体:

<resources>
    <!-- Base application theme. -->
    <style name="Theme.MyTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
        <!-- Primary brand color. -->
        <item name="colorPrimary">@color/purple_500</item>
        <item name="colorPrimaryVariant">@color/purple_700</item>
        <item name="colorOnPrimary">@color/white</item>
        <!-- Secondary brand color. -->
        <item name="colorSecondary">@color/teal_200</item>
        <item name="colorSecondaryVariant">@color/teal_700</item>
        <item name="colorOnSecondary">@color/black</item>
        <!-- Status bar color. -->
        <item name="android:statusBarColor">@color/status_bar_white</item>
        <item name="android:windowLightStatusBar">true</item>
        <item name="android:fontFamily">@font/montserrat</item>
        <!-- Customize your theme here. -->
        <item name="fontFamily">@font/montserrat</item>
    </style>

</resources>
xqkwcwgp

xqkwcwgp1#

调用Typeface.NORMALTypeface.BOLD会创建一个没有任何自定义字体的预设字体,并且只设置字体粗细。您要做的是首先创建一个montserrat字体的字体,然后创建一个具有该字体和指定粗细的字体。
基本上是这样的:

val montserratTypeface = Typeface.createFromAsset(assets, "fonts/montserrat.ttf")

// params: typeface family, weight(700 is bold, 400 is normal), boolean italic
val boldMontserratTypeface = Typeface.create(montserratTypeface, 700, false)

可能有一种方法可以直接使用fontfamily和weight创建字体,但我还没有详细检查字体类,您可以研究一下here

相关问题