Skip to content

Instantly share code, notes, and snippets.

@Johnyoat
Last active January 14, 2024 15:19
Show Gist options
  • Save Johnyoat/040ca5224071d01b3f3dfc6cd4d026f7 to your computer and use it in GitHub Desktop.
Save Johnyoat/040ca5224071d01b3f3dfc6cd4d026f7 to your computer and use it in GitHub Desktop.
Changing or setting one font for all text font in android in Kotlin
class MyApp : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val typefaceUtil = TypefaceUtil()
typefaceUtil.overridefonts(this,"SERIF","fonts/roboto.ttf")
}
}
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- you should set typeface which you want to override with TypefaceUtil -->
<item name="android:typeface">serif</item>
</style>
</resources>
import android.content.Context
import android.graphics.Typeface
import timber.log.Timber
class TypefaceUtil{
fun overridefonts(context: Context, defaultFontToOverride:String, customFontFileNameInAssets:String){
try {
val customTypeface = Typeface.createFromAsset(context.assets,customFontFileNameInAssets)
val defaultTypefaceField = Typeface::class.java.getDeclaredField(defaultFontToOverride)
defaultTypefaceField.isAccessible = true
defaultTypefaceField.set(null,customTypeface)
}catch (e:Exception){
Timber.e("Cannot set font $customFontFileNameInAssets instead of $defaultFontToOverride")
}
}
}
@Aroniez
Copy link

Aroniez commented Sep 25, 2019

Is there away I can set default different fonts for bold and normal texts such that all normal texts have their own fonts while bold texts have different font?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment