我正在致力于Android应用程序的全球化。我必须提供选项,从应用程序中选择不同的地区。我在我的活动(HomeActivity)中使用了以下代码,其中我提供了更改区域设置的选项
Configuration config = new Configuration();
config.locale = selectedLocale; // set accordingly
// eg. if Hindi then selectedLocale = new Locale("hi");
Locale.setDefault(selectedLocale); // has no effect
Resources res = getApplicationContext().getResources();
res.updateConfiguration(config, res.getDisplayMetrics());只要没有像屏幕旋转这样的配置更改,就可以很好地工作,其中区域设置默认为android系统级区域设置,而不是由代码设置的区域设置。
Locale.setDefault(selectedLocale);我能想到的一种解决方案是使用SharedPreferences持久化用户选择的地区,并在每个活动的onCreate()方法中将地区设置为持久化地区,因为每次配置更改都会一次又一次地调用onCreate()。有没有更好的方法来做到这一点,这样我就不必在每个活动中都这样做了。
基本上我想要的是-一旦我在我的HomeActivity中更改/设置了某个地区,我希望我的应用程序中的所有活动都使用该地区本身,而不管任何配置changes....unless,直到它从提供更改地区选项的应用程序的HomeActivity更改为其他地区。
发布于 2014-04-29 05:33:36
尽管此答案中陈述的解决方案在一般情况下有效,但我发现自己添加到了我的首选项屏幕中:
<activity android:name="com.example.UserPreferences"
android:screenOrientation="landscape"
android:configChanges="orientation|keyboardHidden|screenSize">
</activity>这是因为当应用程序处于横向模式而首选项屏幕处于纵向模式时,更改区域设置并返回到应用程序可能会导致问题。将两者都设置为横向模式可防止这种情况发生。
一般解决方案
您需要在应用程序级别更改区域设置,以便其效果随处可见。
public class MyApplication extends Application
{
@Override
public void onCreate()
{
updateLanguage(this);
super.onCreate();
}
public static void updateLanguage(Context ctx)
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
String lang = prefs.getString("locale_override", "");
updateLanguage(ctx, lang);
}
public static void updateLanguage(Context ctx, String lang)
{
Configuration cfg = new Configuration();
if (!TextUtils.isEmpty(lang))
cfg.locale = new Locale(lang);
else
cfg.locale = Locale.getDefault();
ctx.getResources().updateConfiguration(cfg, null);
}
}然后你必须在你的清单中写下:
<application android:name="com.example.MyApplication" ...>
...
</application>https://stackoverflow.com/questions/22402491
复制相似问题