更改应用程序的语言

时间:2016-04-26 12:30:03

标签: android locale

我正在尝试更改应用的语言。

我实现了这段代码:

public static void setLocale(Resources res, String lang) {
    Configuration conf =  new Configuration(res.getConfiguration());

    switch (lang) {
        case "French" :
            conf.locale = new Locale("fr");
            break;
        case "Dutch" :
            conf.locale = new Locale("nl");
            break;
        case "English" :
            conf.locale = new Locale("en");
            break;
    }
    res.updateConfiguration(conf, res.getDisplayMetrics());
}

然后我使用以下代码刷新我的活动:

Intent refresh = new Intent(getActivity(), HomeActivity.class);
getActivity().finish();
startActivity(refresh);

此代码有效,但当我关闭应用程序(从后台删除)并重新打开它时,语言将返回到我的设备的默认语言。

重新打开我的应用时,有没有办法保留所选语言?

2 个答案:

答案 0 :(得分:2)

您可以存储在默认的共享首选项中:

PreferenceManager.getDefaultSharedPreferences().edit().putString("Locale", localVal).commit();

并且每次应用程序开始通过以下方式进行检索:

locale = PreferenceManager.getDefaultSharedPreferences().getString("Locale", "defaultValue");

答案 1 :(得分:0)

我在我的应用程序中使用它,它工作正常,试试希望它会帮助你

 public static void changeLanguageSettings(Context context,String language){        
    try{
        Locale mLocale = new Locale(language);
        Resources res = context.getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration configuration = res.getConfiguration();
        Configuration newConfig = new Configuration(configuration);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){
            newConfig.setLocale(mLocale);
        }else{
            newConfig.locale = mLocale;
        }
        context.getResources().updateConfiguration(newConfig, dm);          
    }catch(Exception e){
        e.printStackTrace();            
    }       
}
相关问题