如何获取当前Android应用程序显示的语言(区域设置)?

34

如何获取当前 Android 应用程序用于向用户显示文本的语言(区域设置)?

我知道可以使用Locale.getDefault()来获取默认的操作系统语言环境。但是,如果应用程序不支持该语言环境,则它可能与用于显示文本和其他资源的应用程序使用的语言环境不同。


我需要确定应用程序所显示的语言(区域设置),以便应用程序可以将语言传递给服务器,从而可以在返回的结果中进行本地化。

6个回答

51

我的解决方案是在strings.xml中添加键值对locale=<locale code>,这样context.getResources().getString(R.string.locale)将返回用于当前语言环境的语言代码。


我猜这个解决方案应该是你问题的一部分。 - Yaqub Ahmad
2
@YaqubAhmad 我后来想到了这个解决方案。但我仍在等待可能更好的解决方案。 - Aleksejs Mjaliks
1
我喜欢这个解决方案,因为只有在使用我的翻译资源时,我才能保证获得区域设置代码。那是我想要的唯一时间。否则,如果我在获取区域设置时犯了某种错误,我可能会在一个语言中获得日期和其他字符串资源在另一种语言中。 - Suragch
2
十年过去了,这仍然是获取所需区域设置的唯一方法。 - Alex Semeniuk

33

这取决于你的应用配置,你可以使用以下代码获取它:

getResources().getConfiguration().locale

这与之前的不同

Locale.getDefault()

同时展示应用程序使用的Locale,这可能会有所不同。

它可能会有所不同,因为开发人员可以通过更新应用程序配置来更改它,参见:Resources.updateConfiguration


你列出的第一个函数的文档说:“当前用户对于语言环境的偏好,对应于语言环境资源限定符”。如果这是“当前用户偏好”,那么它与第二个函数有什么不同?无论如何,Locale类的哪个函数可以调用以获取语言环境代码字符串(相当于资源扩展名),以便将其传回服务器(如原始问题中所述)? - Tom
这个答案提到了获取Locale的正确方法(第一行代码)。但是错误的是有一个区别:Locale.getDefault()等同于第一个例子。如果你想要获取语言代码,你需要调用getLanguage() - caw
17
很遗憾,这并不符合我的需求。如果设置系统语言为丹麦语(Dansk),getResources().getConfiguration().locale返回的是da_DK,而显示的是英文字符串(来自values/strings.xml)。 - Aleksejs Mjaliks
2
getResources().getConfiguration().locale.getLanguage(); 是正确的方式。 - Martijn Symaeys
两者都无法正常工作:我的应用程序支持英语(默认)和德语,我将模拟器的语言设置为1.丹麦语和2.德语(瑞士)。然后,我的应用程序正确选择了德语,但Locale.getDefault()显示为"de_CH",而不是设备的语言(丹麦语)。getResources().getConfiguration().getLocales().get(0)(无论是否使用getLanguage())正确显示为"德语",但是如果设备使用的是应用程序不支持的语言(例如丹麦语+意大利语),那么Locale.getDefault()getResources().getConfiguration().getLocales().get(0)都会返回设备的语言,而不是应用程序的语言。 - undefined

5
以下代码对我有效:
@TargetApi(Build.VERSION_CODES.M)
private String getCurrentDefaultLocaleStr(Context context) {
    Locale locale = context.getResources().getConfiguration().locale;
    return locale.getDefault().toString();
}

注意:在Build.VERSION_CODES.N中获取区域设置的方法略有变化。对于N及以上版本,代码应如下所示;但是,我只在上面的代码块中为M及以下版本执行此操作,而且它也适用于N及以上版本。

    // Build.VERSION_CODES.N
    Locale locale = context.getResources().getConfiguration().getLocales().get(0);

我得到了我所支持的国家语言如下:
English:             en 
Traditional Chinese: zh_TW_#Hant 
Simplified Chinese:  zh_CN_#Hans
Spanish:             es_ES
French:              fr_FR
Japanese:            ja_JP
German:              de_DE

以下是以不同格式提供相同区域信息的方法列表:

locale.getDefault().getCountry();
locale.getDefault().getISO3Language();
locale.getDefault().getISO3Country();
locale.getDefault().getDisplayCountry();
locale.getDefault().getDisplayName();
locale.getDefault().getDisplayLanguage();
locale.getDefault().getLanguage();
locale.getDefault().toString();

请注意,保留了html标签。

Locale类中没有非静态的getDefault()方法。 - arekolek

1
在 Kotlin 中,您可以将以下扩展函数添加到您的项目中:
fun Context.getCurrentLocale(): Locale {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
        this.resources.configuration.locales.get(0);
    } else{
        this.resources.configuration.locale;
    }
}

使用时不会出现任何警告:

val locale = applicationContext.getCurrentLocale()


1
你可以使用以下代码。 例如,下面介绍的功能可以放置在扩展Application类的类中。
public class MyApplication extends Application {
    ...
    public static String APP_LANG;
    private Context ctx = getBaseContext();
    private Resources res = ctx.getResources();
    public SharedPreferences settingPrefs;
    ...

    public void restoreAppLanguage(){
    /**
    *Use this method to store the app language with other preferences.
    *This makes it possible to use the language set before, at any time, whenever 
    *the app will started.
    */
        settingPrefs = getSharedPreferences("ConfigData", MODE_PRIVATE);
        String lang = settingPrefs.getString("AppLanguage", "");
        if(!settingPrefs.getAll().isEmpty() && lang.length() == 2){
            Locale myLocale;
            myLocale = new Locale(lang);
            Locale.setDefault(myLocale);
            Configuration config = new Configuration();
            config.locale = myLocale;
            res.updateConfiguration( config, res.getDisplayMetrics() );
        }
    }

    public void storeAppLanguage(int lang) {
    /**
    *Store app language on demand
    */
        settingPrefs = getSharedPreferences("ConfigData", MODE_PRIVATE);
        Editor ed = settingPrefs.edit();

        Locale myLocale;
        myLocale = new Locale(lang);
        Locale.setDefault(myLocale);
        Configuration config = new Configuration();
        config.locale = myLocale;
        res.updateConfiguration( config, res.getDisplayMetrics() );
        ed.putString("AppLanguage", lang);

        ed.commit();
    }

    public void setAppLanguage(String lang){
    /**
    *Use this method together with getAppLanguage() to set and then restore
    *language, whereever you need, for example, the specifically localized
    *resources.
    */
        Locale myLocale;
        myLocale = new Locale(lang);
        Locale.setDefault(myLocale);
        Configuration config = new Configuration();
        config.locale = myLocale;
        res.updateConfiguration( config, res.getDisplayMetrics() );
    }

    public void getAppLanguage(){
    /**
    *Use this method to obtain the current app language name
    */
        settingPrefs = getSharedPreferences("ConfigData",MODE_PRIVATE);
        String lang = settingPrefs.getString("AppLanguage", "");
        if(!settingPrefs.getAll().isEmpty() && lang.length() == 2){
            APP_LANG = lang;
        }
        else APP_LANG = Locale.getDefault().getLanguage();
    }
}

然后在主代码中的任何位置,我们可以编写:

public class MainActivity extends ActionBarActivity {
    ...
    MyApplication app;
    ... 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        app = (MyApplication)getApplicationContext();
        ...
        if(settingPrefs.getAll().isEmpty()){
            //Create language preference if it is not
            app.storeAppLanguage(Locale.getDefault().getLanguage());
        }

        //Restore previously used language
        app.restoreAppLanguage();
        ...
    }
    ...
    void SomethingToDo(){
        String lang = "en"; //"fr", "de", "es", "it", "ru" etc.
        ...
        app.getAppLanguage();
        app.setAppLanguage(lang);
        ...
        //do anything
        ...
        app.setAppLanguage(app.APP_LANG);
    }
    ...
}

在你的情况下,你可以简单地使用getAppLanguage(),然后检查公共变量APP_LANG来获取当前使用的语言。

0
 public boolean CheckLocale(Context context, String app_language) {
        Locale myLocale = new Locale(app_language);
        Resources res = context.getResources();
        Configuration conf = res.getConfiguration();
        conf.locale = myLocale;
        if(res.getConfiguration().locale==myLocale)
            return true;
        else 

         return false;

    }

请使用这个方法。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接