在运行时更改语言环境? [英] Change the locale at runtime?

查看:26
本文介绍了在运行时更改语言环境?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个 Android 应用程序,可用作远程 PC 程序的客户端.我们想添加一个功能,以便 PC 可以指示 Android 应用程序在运行时更改其区域设置,即启动应用程序;将其与 PC 通信;稍后,PC 会告诉应用程序切换到西班牙语或中文.

We have an Android app that functions as a client for a remote PC program. We'd like to add a feature so the PC can instruct the Android app to change its locale at runtime, i.e., start the app; put it in communication with the PC; sometime later the PC tells the app to switch to, say, Spanish or Chinese.

我们已经为它们各自的语言环境设置了所有布局和字符串资源.我们的应用是用户看到的唯一应用,因此设备的其余部分是否保持英文并不重要.

We already have all the layout and string resources set up for their respective locales. Our app is the only app the user sees so it doesn't matter if the rest of the device stays in English.

在 Android 中以编程方式更改语言上有另一个线程,但它没有似乎没有得出结论.

There is another thread on this at Change language programmatically in Android but it doesn't seem to reach a conclusion.

我可以放...

Locale locale = new Locale(sTheNewLocale);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
      getBaseContext().getResources().getDisplayMetrics());

...在 setContentView() 之前的 onCreate() 中,但如果我想在屏幕启动并运行后更改语言环境,这并没有真正的帮助.有没有办法在 Activity 已经运行后重新加载内容视图?所以是否有任何实用的方法可以可靠地即时更改语言环境,还是我必须告诉我的老板除了在启动应用程序之前将整个设备设置为新的语言环境之外,这是无法做到的?

. . . in onCreate() before the setContentView() but that doesn't really help if I want to change the locale after my screen is up and running. Is there a way to REload the content view after the Activity is already running? So is there any practical way to change locales on-the-fly reliably or do I have to tell my boss it can't be done except for setting the whole device to the new locale before starting the app?

推荐答案

从 API 11 开始你可以使用 recreate 所以可以在你的活动中使用这个方法:

Since API 11 you can use recreate so can make this method in your activity:

private void restartInLocale(Locale locale)
{
    Locale.setDefault(locale);
    Configuration config = new Configuration();
    config.locale = locale;
    Resources resources = getResources();
    resources.updateConfiguration(config, resources.getDisplayMetrics());
    recreate();
}

这篇关于在运行时更改语言环境?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆