-2

i have some question here. i just want to know, how to make an if else statement for the system language that currently being used? i have a project where, i need to use different font when the system language is changed. so my guess is by creating the if else statement would solve this. my code is like below:

final Typeface en = Typeface.createFromAsset(getAssets(), "LCfont-en.ttf");
final Typeface ar = Typeface.createFromAsset(getAssets(), "LCfont-ar.ttf");
final Typeface cn = Typeface.createFromAsset(getAssets(), "LCfont-cn.ttf");
final Typeface tw = Typeface.createFromAsset(getAssets(), "LCfont-tw.ttf");
final Typeface th = Typeface.createFromAsset(getAssets(), "LCfont-th.ttf");

TextView text1 = (TextView) view.findViewById(R.id.TV);

text1.setTypeface(en);
text1.setTypeface(ar);
text1.setTypeface(cn);
text1.setTypeface(tw);
text1.setTypeface(th);

so above is the code, i want to use different font when system language is changed. any help very appreciate. thanks!

squall leonhart
  • 301
  • 1
  • 5
  • 16

1 Answers1

0

Your can use Locale class like this to retrieve current locale:

String localeCode = Locale.getDefault().getLanguage();
if ("en".equals(localCode)) {
    // ...
} else if ("es".equals(localCode)) {
    // ...
}

Alternative

If you have only a few amount of typeface. You could also define your asset font name in resource and override it by configuration. For example, in your values/strings.xml:

<string name="typeface_path">LCfont-en.ttf</string>

and in values-ar/strings.xml:

<string name="typeface_path">LCfont-ar.ttf</string>

and the equivalent for other languages. Then in your code you could use :

final Typeface typeface = Typeface.createFromAsset(getAssets(), getString(R.string.typeface_path));
TextView text1 = (TextView) view.findViewById(R.id.TV);
text1.setTypeface(typeface);
Médéric
  • 938
  • 4
  • 12
  • thanks!! your first answer is work. but how to differentiate between simplfied chinese and traditional chinese? both of them use "zh". – squall leonhart May 26 '15 at 10:52
  • You can use Locale.getDefault().toString() instead of Locale.getDefault().getLanguage(). You will have somthing like zh_CN or zh_TW. Is that what you need? – Médéric May 26 '15 at 11:19
  • oh really? so the code will be like: `"zh_TW".equals(localCode)`. am i right sir? btw, i want to try your alternative answer but, i got error in my code since i put my code in the function `private void getString(final View view)`. the error is at the `getString(R.string.typeface_path)` itself. the error is `The method getString(View) in the type ChannelCall is not applicable for the arguments (int)`. do you what is this mean? – squall leonhart May 27 '15 at 01:42
  • You're right. getString is a method from Context class. Adapt for your code ;) – Médéric May 27 '15 at 07:09