Last active
January 14, 2024 15:19
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyApp : AppCompatActivity() { | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
val typefaceUtil = TypefaceUtil() | |
typefaceUtil.overridefonts(this,"SERIF","fonts/roboto.ttf") | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
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?