4

I made an application for android and i have two languages (english - greek) and i want when the device has english locale to have different fonts than it has in the greek language.

I used

String loc = Locale.getDefault().getISO3Language();

to get the iso3Language (eng, ell, deu....) and then i used an if command

if(loc=="eng"){
        Typeface font1 = Typeface.createFromAsset(getAssets(), "MISTRAL.TTF");
        txt1.setTypeface(font1);
        txt1.setText(R.string.app_name);
    }
    else{
        Typeface font1 = Typeface.createFromAsset(getAssets(), "SNAP.TTF");
        txt1.setTypeface(font1);
        txt1.setText(R.string.app_name);
    }

but it doesn't recognise it and even when i have english locale it executes the else part of the code!! Can you help me please?? Thank you!!

iliamyro
  • 43
  • 1
  • 3

2 Answers2

3

IMHO your aproach is wrong. This can be done easily on resorce level. No line of code is needed!

Create xml file with values in 'res/values' directory for english version (and all other languages). In this file create new style which sets typeface. This will look more or less like this (i don't have SDK here so there might be some mistakes):

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="CustomText" parent="@style/Text">
        <item name="android:typeface">MISTRAL.TTF</item>
        <item name="android:textColor">#008</item>
    </style>
</resources>

Create same file in 'res/values-el' (Greek, Modern) and define same style there (just copy paste) but with alternative typeface.

In you layout files apply this style in all places where you need alter the font depending on locale. There is property 'style' (it doesn't have a namespace) to set for views. Autocompletion should lead you by heand.

Marek R
  • 32,568
  • 6
  • 55
  • 140
  • I'm pretty sure you can't use `MISTRAL.TTF` there out of the blue in styles.xml – John61590 Dec 02 '16 at 08:22
  • Apparently you are right. I didn't had time to verify this. At least this applies to custom fonts. There is workaround for that http://stackoverflow.com/a/6746775/1387438 Worst case scenario I would use custom value in xml and use this value in code, but linked solution looks better. – Marek R Dec 02 '16 at 13:18
1

In java, you can't compare string using ==. Use the equals method instead.

This this tutorial for a more in depth answer.

Snicolas
  • 37,840
  • 15
  • 114
  • 173