我有一个活动,我以编程方式将区域设置设置为“de”,但它不能按预期工作,并显示手动设置的默认语言(英文文本)。请帮忙
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Programmatically sets the locale and language
Locale locale = new Locale("de");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,getBaseContext().getResources().getDisplayMetrics());
Toast.makeText(getApplicationContext(),Locale.getDefault().getDisplayLanguage(),Toast.LENGTH_LONG).show();
setContentView(R.layout.main);
Intent intent=new Intent(LatestLocalizationActivity.this,AnotherActivity.class);
startActivity(intent);
}
答案 0 :(得分:5)
您是否在res-> value-de文件夹中添加了Strings.xml文件?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Programmatically sets the locale and language
setContentView(R.layout.main);
config = getBaseContext().getResources().getConfiguration();
locale = new Locale("de");
Locale.setDefault(locale);
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
refresh();
Toast.makeText(getApplicationContext(),Locale.getDefault().getDisplayLanguage(),Toast.LENGTH_LONG).show();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
Configuration config = getBaseContext().getResources().getConfiguration();
// refresh your views here
Locale.setDefault(locale);
config.locale = locale;
super.onConfigurationChanged(newConfig);
}
private void refresh() {
finish();
Intent myIntent = new Intent(yourActivity.this, yourActivity.class);
startActivity(myIntent);
}
答案 1 :(得分:3)
请注意,尽管您可能能够通过各种方式进行操作来实现这样的功能,但Android目前还不支持以强大的方式执行此操作。特别是,框架在资源中处理当前配置,并在认为合适时更新它。您将与此作斗争,并且您不太可能没有配置恢复到系统区域设置的情况。
答案 2 :(得分:2)
这对我有用:
public static void changeLocale(Context context, Locale locale) {
Configuration conf = context.getResources().getConfiguration();
conf.locale = locale;
Locale.setDefault(locale);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
conf.setLayoutDirection(conf.locale);
}
context.getResources().updateConfiguration(conf, context.getResources().getDisplayMetrics());
}
请使用您的ACTIVITY CONTEXT而不是您的申请背景。