Im using custom font in my android app. I want to set this custom font to app default font (as fallback) but I still want to use the TextView
textAppearance
property to set font and text style.
It looks like setting textViewStyle
or fontFamily
in my app base theme, allays overrides TextView
textAppearance
style?
<style name="MyApp.Base" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Overriding fontFamily also overrides textView textAppearance -->
<item name="android:fontFamily">@font/open_sans</item>
<!-- Overriding textViewStyle also overrides textView textAppearance -->
<item name="android:textViewStyle">@style/DefaultTextAppearance</item>
</style>
<style name="DefaultTextAppearance" parent="TextAppearance.AppCompat">
<item name="android:textStyle">normal</item>
<item name="fontFamily">@font/open_sans_regular</item>
</style>
<style name="BoldTextAppearance" parent="TextAppearance.AppCompat">
<item name="android:textStyle">normal</item>
<item name="fontFamily">@font/open_sans_extra_bold</item>
</style>
<!-- This textView does not get bold style -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Me happy"
android:textAppearance="@style/BoldTextAppearance" />
View's style attributes has more priority to textAppearance.
In both cases you have fontFamily inside style instead of textAppearance. When you put fontFamily
directly inside base theme, view obtains that style from its activity.
So, instead of setting base fontFamily
value in style, you need to set base TextView's textAppearance:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="android:textViewStyle">@style/TextViewStyle</item>
</style>
<style name="TextViewStyle" parent="@android:style/TextAppearance.Widget.TextView">
<item name="android:textAppearance">@style/DefaultTextAppearance</item>
</style>
<style name="DefaultTextAppearance" parent="TextAppearance.AppCompat">
<item name="android:textStyle">normal</item>
<item name="fontFamily">@font/roboto_regular</item>
</style>
<style name="LobsterTextAppearance" parent="TextAppearance.AppCompat">
<item name="android:textStyle">normal</item>
<item name="fontFamily">@font/lobster</item>
</style>
So, here I have 2 textAppearances: DefaultTextAppearance
, that is used as default for all TextViews and LobsterTextAppearance
, that I use in specific case.
Layout looks like:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Default roboto text" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lobster text"
android:textAppearance="@style/LobsterTextAppearance" />
So, first TextView uses fontFamily from base textAppearance, second one uses overridden @style/LobsterTextAppearance
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With