Home » Android » android – How to get bold style in custom font family?-Exceptionshub

android – How to get bold style in custom font family?-Exceptionshub

Posted by: admin February 26, 2020 Leave a comment

Questions:

I have following custom font family code, and i want to have font weight for that font

abc.xml

<?xml version="1.0" encoding="utf-8"?>
<font-family
    xmlns:android="http://schemas.android.com/apk/res/android">

    <font
        android:font="@font/abc_regular"
        android:fontStyle="normal"
        android:fontWeight="400" />

    <font
        android:font="@font/abc_bold"
        android:fontStyle="normal"
        android:fontWeight="700" />
</font-family>

BaseButton.kt

open class BaseButton : AppCompatButton {

    @JvmOverloads
    constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyleAttr: Int = 0)
            : super(context, attrs, defStyleAttr) {
        setFontFamily()
    }

    private fun setFontFamily() {
        val typeface = ResourcesCompat.getFont(context, R.font.abc)
        this.typeface = typeface
    }
}

screen_layout.xml

<com.aaa.bbb.ccc.BaseButton
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:text="Test"
    android:textStyle="bold"
    android:textFontWeight="700" />

The button does not show bolded text. What is wrong?

How to&Answers:

Because you are setting typeface after the bold style is set up in the parent constructor. Try this one

    private fun setFontFamily() {
        val typeface = ResourcesCompat.getFont(context, R.font.sf_pro)
        val isBold = getTypeface().isBold

        this.setTypeface(typeface, if (isBold) Typeface.BOLD else Typeface.NORMAL)
    }

Answer:

I hope this will work for you.

Add fontFamily attribute in your layout file.

<com.aaa.bbb.ccc.BaseButton
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:text="Test"
    android:fontFamily="@font/abc_bold" />