I make the text bold by setting typeface = Typeface.DEFAULT_BOLD
. It works, but my font (Monserrat) becomes default (Roboto). How can I change the boldness without affecting the font?
Function to set typeface:
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
}
}
How I call it:
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?) {
}
})
}
I specify the font only here:
<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>
CodePudding user response:
Well, calling Typeface.NORMAL
or Typeface.BOLD
creates a preset typeface without any custom font, and only sets the font weight. What you want to do is to create a typeface with the montserrat
font first, then creating the typeface with that font AND the specified weigh.
Basically like this:
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)
There is probably a method to create a typeface directly with the fontfamily and weight, but I haven't really checked the typeface class in detail, you can research it here