Android重新加载资源,更改区域设置:强制重新加载资源的活动?

在AndroidManifest.xml中,将此属性添加到您的Activity中

android:configChanges="locale"

在你的活动中覆盖onConfigurationChanged()

@Override public void onConfigurationChanged(Configuration newConfig) { // refresh your views here super.onConfigurationChanged(newConfig); }

我认为问题是在运行时为应用程序切换语言并在UI中显示本地化消息。 android:configChanges="locale"调用onConfigurationChanged如果在应用程序运行时更改了系统区域设置(在设备设置中),而不是在应用程序代码中更改区域设置,我想这就是你想要完成的。 这就是为什么它不令人耳目一新。

这是我在每个活动onCreate()或onResume()期间使用的方法,具体取决于我的需要(如果我的活动将在用户更改语言设置后恢复,或者将始终使用已设置的语言创建):

从那里我只是手动或从onConfigurationChanged()刷新视图,该方法在此方法完成后调用。

public static void changeLocale(Activity activity, String language) { final Resources res = activity.getResources(); final Configuration conf = res.getConfiguration(); if (language == null || language.length() == 0) { conf.locale = Locale.getDefault(); } else { final int idx = language.indexOf('-'); if (idx != -1) { final String[] split = language.split("-"); conf.locale = new Locale(split[0], split[1].substring(1)); } else { conf.locale = new Locale(language); } } res.updateConfiguration(conf, null); }

我不知道为什么onConfigurationChanged() 。

嘿,sandis,你的意思是当你改变语言时, onConfigurationChanged()方法没有在你的活动中调用吗? 我遇到了同样的问题。 问题可能是这样的:当我们改变语言时,活动转到onDestroy() (你可以试试这个),所以没有人可以调用onConfigurationChanged() 。 当我们再次启动活动时,将调用onCreate() ,而不是onConfigurationChanged() 。 区域设置更改和方向更改可能有所不同。

public void settingLocale(Context context, String language) { Locale locale; Configuration config = new Configuration(); if(language.equals(LANGUAGE_ENGLISH)) { locale = new Locale("en"); Locale.setDefault(locale); config.locale = locale; }else if(language.equals(LANGUAGE_ARABIC)){ locale = new Locale("hi"); Locale.setDefault(locale); config.locale = locale; } context.getResources().updateConfiguration(config, null); // Here again set the text on view to reflect locale change // and it will pick resource from new locale tv1.setText(R.string.one); //tv1 is textview in my activity }

假设你正在通过类似的方式改变语言

private void updateLocale(@NonNull final Context context, @NonNull final Locale newLocale) { final Resources resources = context.getResources(); final DisplayMetrics displayMetrics = resources.getDisplayMetrics(); final Configuration configuration = resources.getConfiguration(); configuration.locale = newLocale; resources.updateConfiguration(configuration, displayMetrics); Locale.setDefault(newLocale); }

您需要在所有当前打开的活动中调用Activity.recreate() ,如果用户在未订阅android:configChanges="locale"更改了系统语言,则会发生这种情况。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值