Changing locale: Force activity to reload resources?

后端 未结 6 1495
感情败类
感情败类 2020-11-30 06:24

So I have a language setting in my application. When the language is switched, I would like all the textviews etc to change language immediately. Currently I just change the

6条回答
  •  误落风尘
    2020-11-30 06:55

    Assuming you're changing the language through something like

    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);
    }
    

    You'll need to call Activity.recreate() in all currently open activities, which is what would happen if the user changed the system language while you were not subscribing to android:configChanges="locale".

提交回复
热议问题