更改Android应用程序资源中的语言

时间:2017-03-25 08:44:04

标签: android

在研究了在Android应用程序中支持多种语言之后,我对如何在应用程序中为不同语言创建资源有了基本的想法,例如我想在我的应用程序中添加西班牙语,所以在我的应用程序中的res方向我添加了值-en目录,直接我已经添加了字符串资源,并且在该资源中我添加了西班牙文本值的字符串,在我的应用程序中默认语言是英语现在我想知道如何将其切换为西班牙语,我准备好资源我只需要将我的应用程序语言更改为西班牙语

1 个答案:

答案 0 :(得分:0)

onCreate()后的setContentView中使用以下代码:

String languageToLoad = "es";
Locale locale = new Locale(languageToLoad);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());

您还必须将值文件夹更改为 values-es 。 values-en适用于英语。希望这会有所帮助。

要更改应用区域设置,请按以下代码操作:

1)创建 LocaleUtils 类:

public class LocaleUtils {

    private static Locale sLocale;

    public static void setLocale(Locale locale) {
        sLocale = locale;
        if(sLocale != null) {
            Locale.setDefault(sLocale);
        }
    }

    public static void updateConfig(ContextThemeWrapper wrapper) {
        if(sLocale != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            Configuration configuration = new Configuration();
            configuration.setLocale(sLocale);
            wrapper.applyOverrideConfiguration(configuration);
        }
    }

    public static void updateConfig(Application app, Configuration configuration) {
        if (sLocale != null && Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
            //Wrapping the configuration to avoid Activity endless loop
            Configuration config = new Configuration(configuration);
            // We must use the now-deprecated config.locale and res.updateConfiguration here,
            // because the replacements aren't available till API level 24 and 17 respectively.
            config.locale = sLocale;
            Resources res = app.getBaseContext().getResources();
            res.updateConfiguration(config, res.getDisplayMetrics());
        }
    }
}

2)在应用程序类

public class YourAppName extends Application {
    public void onCreate(){
        super.onCreate();

        LocaleUtils.setLocale(new Locale("es"));
        LocaleUtils.updateConfig(this, getBaseContext().getResources().getConfiguration());
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        LocaleUtils.updateConfig(this, newConfig);
    }
}

3)记住,您的应用类名称和<application android:name=".YourAppName">应该相同。否则它将无法工作。感谢this回答。

相关问题