gpt4 book ai didi

java - 更改区域设置不会影响字体类型

转载 作者:行者123 更新时间:2023-12-01 17:28:54 24 4
gpt4 key购买 nike

我有两种语言的两个字体目录(fa/en)。在我的应用程序设置中,用户可以更改应用程序语言。我将其更改保存在首选项中并开始主要 Activity 。在 oncreate 方法的第一行 super.oncreate 之前的主要 Activity 中,我根据首选项中保存的语言更改区域设置。应用程序的语言发生了变化,但字体没有变化!关闭并再次打开应用程序后..字体更改已完成。

使用此代码更改语言。

    private void configAppLanguage(){
String lang = PrefManager.getLanguage();
Locale locale = new Locale(lang);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;

getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());

}

使用此代码开始主要 Activity 。

Intent intent = new Intent(LanguageActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);

最佳答案

不要忘记,如果您更改正在运行的 Activity 的区域设置,则需要重新启动它才能使更改生效。只是为了得到一个明确的答案,我使用了一些代码(根据您的上下文进行了更改):

@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(updateBaseContextLocale(base));
}

private Context updateBaseContextLocale(Context context) {
final String language = PrefManager.getLanguage(); // Your helper method to get saved language
final Locale locale = new Locale(language);
Locale.setDefault(locale);

if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
return updateResourcesLocale(context, locale);
}

return updateResourcesLocaleLegacy(context, locale);
}

@TargetApi(Build.VERSION_CODES.N_MR1)
private Context updateResourcesLocale(Context context, Locale locale) {
Configuration configuration = new Configuration(context.getResources().getConfiguration())
configuration.setLocale(locale);
return context.createConfigurationContext(configuration);
}

@SuppressWarnings("deprecation")
private Context updateResourcesLocaleLegacy(Context context, Locale locale) {
final Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();
configuration.locale = locale;
resources.updateConfiguration(configuration, resources.getDisplayMetrics());
return context;
}

每次您的 Activity 启动时,attachBaseContext(Context base) 方法都会被调用并更新您的语言。

希望能帮到你。干杯!

关于java - 更改区域设置不会影响字体类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61163550/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com