在研究了在android应用程序中支持多种语言之后,我对如何在应用程序中为不同语言创建资源有了很好的了解,例如,我希望在我的应用程序中添加西班牙语,因此在我的应用程序中,我在应用程序中添加了值-en目录,并且在该资源中直接添加了字符串资源,并在该资源中添加了带有西班牙语文本值的字符串,在我的应用程序默认语言中,现在我想知道如何将其转换为西班牙语,我已经准备好了资源,我只需要将我的应用程序语言改为西班牙语。
发布于 2017-03-25 08:51:05
在onCreate()
中setContentView
之后使用下面的代码
String languageToLoad = "es";
Locale locale = new Locale(languageToLoad);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
您还必须将值文件夹更改为值-es。价值观-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的回答。
https://stackoverflow.com/questions/43014335
复制相似问题