【问题标题】:How to judge current system language in android? [duplicate]如何判断android中当前的系统语言? [复制]
【发布时间】:2015-08-07 22:25:05
【问题描述】:

我在这里有一些问题。我只是想知道,如何为当前使用的系统语言制作if else 语句?我有一个项目,当系统语言更改时,我需要使用不同的字体。所以我的猜测是通过创建if else 语句可以解决这个问题。我的代码如下:

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);

以上是代码,我想在更改系统语言时使用不同的字体。任何帮助都非常感谢。谢谢!

【问题讨论】:

    标签: java android locale


    【解决方案1】:

    您可以像这样使用 Locale 类来检索当前的语言环境:

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

    替代方案

    如果您只有少量字体。您还可以在资源中定义资产字体名称并通过配置覆盖它。 例如,在您的 values/strings.xml 中:

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

    在 values-ar/strings.xml 中:

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

    以及其他语言的等价物。然后在你的代码中你可以使用:

    final Typeface typeface = Typeface.createFromAsset(getAssets(), getString(R.string.typeface_path));
    TextView text1 = (TextView) view.findViewById(R.id.TV);
    text1.setTypeface(typeface);
    

    【讨论】:

    • 谢谢!!你的第一个答案是工作。但是如何区分简体中文和繁体中文呢?他们都使用“zh”。
    • 您可以使用 Locale.getDefault().toString() 代替 Locale.getDefault().getLanguage()。你会有类似 zh_CN 或 zh_TW 的东西。这是你需要的吗?
    • 哦,真的吗?所以代码将类似于:"zh_TW".equals(localCode)。先生,我说得对吗?顺便说一句,我想尝试您的替代答案,但是由于我将代码放入函数private void getString(final View view) 中,因此我的代码出现错误。错误在getString(R.string.typeface_path) 本身。错误是The method getString(View) in the type ChannelCall is not applicable for the arguments (int)。你这是什么意思?
    • 你是对的。 getString 是 Context 类的一个方法。适应你的代码;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-06
    • 2014-01-26
    • 1970-01-01
    相关资源
    最近更新 更多