I have an android application with english and arabic as choosable langagues. My problem is that I need to use a specific font for each langague.
What is the proper way to implement this ?
My idea was to create two different themes in styles.xml
, like this :
<resources>
<!-- English application theme. -->
<style name="EnglishTheme" parent="Theme.AppCompat.Light.NoActionBar">
... all my others attributes ...
<item name="pathBoldFont">fonts/FontEnglish-Bold.ttf</item>
<item name="pathRegularFont">fonts/FontEnglish-Regular.ttf</item>
<item name="pathThinFont">fonts/FontEnglish-Thin.ttf</item>
</style>
<!-- Arabic application theme. -->
<style name="ArabicTheme" parent="Theme.AppCompat.Light.NoActionBar">
... all my others attributes ...
<item name="pathBoldFont">fonts/FontArabic-Bold.ttf</item>
<item name="pathRegularFont">fonts/FontArabic-Regular.ttf</item>
<item name="pathThinFont">fonts/FontArabic-Thin.ttf</item>
</style>
</resources>
At application runtime, I check user's locale and load the correct theme. But obviously, this is not very DRY, because I have to write twice every other attributes of the theme.
I've read that this is not possible to update programmatically theme attributes (just fonts in my case) so what could be a better solution ?
FYI I use InflationX/Calligraphy for my custom fonts.
just create a custom TextView Class where u set your fonts and in there whenever you get a font u check for the language selected
public class CustomTextView extends android.support.v7.widget.AppCompatTextView {
public CustomTextView (Context context) {
super(context);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.CustomTextView,
0, 0);
try {
int custom_font = a.getInt(R.styleable.CustomTextView_custom_font, 0);
switch (custom_font) {
//Regular
case 0:
if(language == "english")
setTypeface(/*return Typeface Regular for english*/);
else setTypeface(/*return Typeface Regular for arabic*/);
break;
//Bold
case 1:
if(language == "english")
setTypeface(/*return Typeface Boldfor english*/);
else setTypeface(/*return Typeface Boldfor arabic*/);
break;
}
} finally {
a.recycle();
}
}
public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
and in your attr.xml
<declare-styleable name="CustomTextView">
<attr name="custom_font" format="string">
<enum name="regular" value="0" />
<enum name="bold" value="1" />
</attr>
</declare-styleable>
Use it like this
<CustomTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:custom_font="bold"/>