Skip to content

Instantly share code, notes, and snippets.

@tungphan-agilityio
Forked from Johnyoat/MyApp.kt
Created September 24, 2019 17:28
Show Gist options
  • Save tungphan-agilityio/1a202000fb23965cc8d3cf8f66d0dd2c to your computer and use it in GitHub Desktop.
Save tungphan-agilityio/1a202000fb23965cc8d3cf8f66d0dd2c 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")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment