如何以编程方式更改语言?

7
我希望您能编写程序来更改语言。
因此,我已经构建了两个XML文件。
values-it
-->string.xml

values-en
-->string.xml

这是用于更改整个应用程序语言的MainActivity代码:
//意大利语
Resources res = getApplicationContext().getResources();
DisplayMetrics dm = res.getDisplayMetrics();
android.content.res.Configuration conf = res.getConfiguration();
conf.locale = new Locale("it");
res.updateConfiguration(conf, dm);

//中文

Resources res2 = getApplicationContext().getResources();
DisplayMetrics dm2 = res2.getDisplayMetrics();
android.content.res.Configuration conf2 = res2.getConfiguration();
conf2.locale = new Locale("en");
res2.updateConfiguration(conf2, dm2);

现在,如果我设置英语语言(例如),代码将无错误执行,但标签不会更改其文本。
如果我更改设备的方向,则标签会正确更改其文本。
现在,我该如何修改我的代码以自动刷新标签?

尝试在onResume()中调用您的代码。 - Mehta
1
嗨,这里有一个链接告诉你如何在不关闭活动的情况下重新加载更改:https://dev59.com/43E85IYBdhLWcg3wtV71 - Miguel Benitez
conf2.locale和res2.updateConfiguration()已经过时了。:S - baquiax
5个回答

10
 AlertDialog.Builder builder = new AlertDialog.Builder(DashboardActivity.this);
            builder.setTitle(R.string.languages);
            // Add the buttons
            builder.setPositiveButton(R.string.english, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    String languageToLoad = "en"; // your language
                    Locale locale = new Locale(languageToLoad);
                    Locale.setDefault(locale);
                    Configuration config = new Configuration();
                    config.locale = locale;
                    getBaseContext().getResources().updateConfiguration(config,
                            getBaseContext().getResources().getDisplayMetrics());
                    dialog.dismiss();
                    rEditor.putString("language", languageToLoad);
                    rEditor.commit();



                    Intent refresh = new Intent(DashboardActivity.this, DashboardActivity.class);
                    startActivity(refresh);
                    finish();

                }
            });
            builder.setNegativeButton(R.string.gujarati, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // User cancelled the dialog

                    String languageToLoad = "gu"; // your language
                    Locale locale = new Locale(languageToLoad);
                    Locale.setDefault(locale);
                    Configuration config = new Configuration();
                    config.locale = locale;
                    getBaseContext().getResources().updateConfiguration(config,
                            getBaseContext().getResources().getDisplayMetrics());
                    dialog.dismiss();
                    rEditor.putString("language", languageToLoad);
                    rEditor.commit();


                    Intent refresh = new Intent(DashboardActivity.this, DashboardActivity.class);
                    startActivity(refresh);
                    finish();

                }
            });

            builder.create().show();

你需要重新加载活动以显示新的语言文本,意味着重启。


什么是rEditor - Choletski
sharedPreference 编辑器用于保存数据。https://developer.android.com/training/basics/data-storage/shared-preferences.html - Ramchandra Singh
resource.updateConfiguration已被弃用。现在有什么替代方案? - Lalit Jadav
请查看此链接... https://dev59.com/MVkS5IYBdhLWcg3wMkBJ#40291570 - Ramchandra Singh
如何从SharedPreferences检查语言并在应用程序启动时更改语言,以便不必重新启动应用程序?应该在哪个位置进行此操作? - Slava

5

你需要刷新你的活动才能加载资源,在改变方向时会自动执行此操作。试试这个方法:

private void restartActivity() { 
 Intent intent = getIntent(); 
 finish(); 
 startActivity(intent);
}

调用recreate()方法难道不比编写自定义方法简单吗? - Sam

3
如果您还没有解决问题,可以尝试这个方法。对我有用,希望能帮到您。日后可以参考。
mSwitch = (Switch) findViewById(R.id.language_switch);

    mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                if (isChecked){
                    mSwitch.setTextColor(Color.GRAY);
                    String languageToLoad = "es";
                    Locale locale = new Locale(languageToLoad);
                    Locale.setDefault(locale);
                    Configuration configuration = new Configuration();
                    configuration.setLocale(locale);
                    Toast.makeText(getApplicationContext(), "spanish is set", Toast.LENGTH_SHORT).show();
                    getBaseContext().getResources().updateConfiguration(configuration, getBaseContext().getResources().getDisplayMetrics());
                } else {
                    String languageToLoad = "en";
                    Locale locale = new Locale(languageToLoad);
                    Locale.setDefault(locale);
                    Configuration configuration = new Configuration();
                    configuration.setLocale(locale);
                    Toast.makeText(getApplicationContext(), "english is set", Toast.LENGTH_SHORT).show();
                    getBaseContext().getResources().updateConfiguration(configuration, getBaseContext().getResources().getDisplayMetrics());
                }
        }
    });

2
最好的方法是将所有的TextView.setText()放在一个方法中。在你的onResume();中调用该方法来进行第一次设置。然后当你重置语言时,再次调用该方法。(当你改变方向时,Activity会经过onStart()onResume()等方法)

不仅仅是关于字符串...有时候方向也很重要,RTL或LTR。 - Muhammad Naderi
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Flummox - don't be evil SE
实际上我挖掘了更多,找到了正确的解决方案,并将其放在了 gist 上:https://gist.github.com/muhammad-naderi/0ff264e6cc07df904bc88a9f7efbe57d - Muhammad Naderi

0
这是我们的做法: < p > < code > com.android.internal.app.LocalePicker.updateLocales(LocaleList locales)

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