jjzjj

Android context.getResources.updateConfiguration() 已弃用

coder 2023-05-08 原文

就在最近 context.getResources()。 updateConfiguration()已在 Android API 25 中弃用,建议使用上下文。 createConfigurationContext()而是。

有谁知道如何使用 createConfigurationContext 来覆盖 android 系统语言环境?

在此之前由以下人员完成:

Configuration config = getBaseContext().getResources().getConfiguration();
config.setLocale(locale);
context.getResources().updateConfiguration(config,
                                 context.getResources().getDisplayMetrics());

最佳答案

灵感来自 Calligraphy ,我最终创建了一个上下文包装器。 就我而言,我需要覆盖系统语言,以便为我的应用用户提供更改应用语言的选项,但这可以使用您需要实现的任何逻辑进行自定义。

    import android.annotation.TargetApi;
    import android.content.Context;
    import android.content.ContextWrapper;
    import android.content.res.Configuration;
    import android.os.Build;
    
    import java.util.Locale;
    
    public class MyContextWrapper extends ContextWrapper {

    public MyContextWrapper(Context base) {
        super(base);
    }

    @SuppressWarnings("deprecation")
    public static ContextWrapper wrap(Context context, String language) {
        Configuration config = context.getResources().getConfiguration();
        Locale sysLocale = null;
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
            sysLocale = getSystemLocale(config);
        } else {
            sysLocale = getSystemLocaleLegacy(config);
        }
        if (!language.equals("") && !sysLocale.getLanguage().equals(language)) {
            Locale locale = new Locale(language);
            Locale.setDefault(locale);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                setSystemLocale(config, locale);
            } else {
                setSystemLocaleLegacy(config, locale);
            }
            
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
             context = context.createConfigurationContext(config);
        } else {
             context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());
            }
        return new MyContextWrapper(context);
    }

    @SuppressWarnings("deprecation")
    public static Locale getSystemLocaleLegacy(Configuration config){
        return config.locale;
    }

    @TargetApi(Build.VERSION_CODES.N)
    public static Locale getSystemLocale(Configuration config){
        return config.getLocales().get(0);
    }

    @SuppressWarnings("deprecation")
    public static void setSystemLocaleLegacy(Configuration config, Locale locale){
        config.locale = locale;
    }

    @TargetApi(Build.VERSION_CODES.N)
    public static void setSystemLocale(Configuration config, Locale locale){
        config.setLocale(locale);
    }
}

要注入(inject)您的包装器,请在每个 Activity 中添加以下代码:

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(MyContextWrapper.wrap(newBase,"fr"));
}

2020 年 12 月 22 日更新 android Material library 实现 ContextThemeWrapper 支持深色模式后,语言设置会中断,语言设置会丢失。经过几个月的头疼,通过在Activity和Fragment的onCreate方法中添加以下代码解决了问题

Context context = MyContextWrapper.wrap(this/*in fragment use getContext() instead of this*/, "fr");
   getResources().updateConfiguration(context.getResources().getConfiguration(), context.getResources().getDisplayMetrics());

2018 年 10 月 19 日更新 有时在方向更改或 Activity 暂停/恢复后,配置对象会重置为默认系统配置,结果我们将看到应用程序显示英文“en”文本,即使我们使用法语“fr”语言环境包装了上下文。因此,作为一种良好做法,切勿将 Context/Activity 对象保留在 Activity 或 fragment 的全局变量中。

此外,在 MyBaseFragment 或 MyBaseActivity 中创建和使用以下内容:

public Context getMyContext(){
    return MyContextWrapper.wrap(getContext(),"fr");
}

这种做法将为您提供 100% 无错误的解决方案。

关于Android context.getResources.updateConfiguration() 已弃用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40221711/

有关Android context.getResources.updateConfiguration() 已弃用的更多相关文章

  1. ruby-on-rails - 我更新了 ruby​​ gems,现在到处都收到解析树错误和弃用警告! - 2

    简而言之错误:NOTE:Gem::SourceIndex#add_specisdeprecated,useSpecification.add_spec.Itwillberemovedonorafter2011-11-01.Gem::SourceIndex#add_speccalledfrom/opt/local/lib/ruby/site_ruby/1.8/rubygems/source_index.rb:91./opt/local/lib/ruby/gems/1.8/gems/rails-2.3.8/lib/rails/gem_dependency.rb:275:in`==':und

  2. ruby - 有没有办法让 2.4.0 中的 Ruby 弃用警告静音? - 2

    从Ruby2.4.0开始,对于使用某些已弃用的功能,会出现弃用警告。例如,Bignum、Fixnum、TRUE和FALSE都会触发弃用警告。当我修复我的代码时,有相当多的代码我希望它保持沉默,尤其是在Rails中。我该怎么做? 最佳答案 moduleKerneldefsuppress_warningsoriginal_verbosity=$VERBOSE$VERBOSE=nilresult=yield$VERBOSE=original_verbosityreturnresultendend>>X=:foo=>:foo>>X=:bar

  3. ruby-on-rails - 从 gem 生成的静音弃用警告 - 2

    我正在使用unscoped_associations我的Rails5.0.0.1应用程序中的gem。我收到这个弃用警告:DEPRECATIONWARNING:alias_method_chainisdeprecated.Please,useModule#prependinstead.Frommodule,youcanaccesstheoriginalmethodusingsuper.(calledfromat/home/rhl/myapp/config/application.rb:8)DEPRECATIONWARNING:alias_method_chainisdeprecated.

  4. ruby-on-rails - Rails group_by 是否已弃用? - 2

    我有一个要分组的数组,“group_by”函数似乎适合我的情况。http://apidock.com/rails/Enumerable/group_by我在Rails3.2.13中使用它。grouped_array=my_array.group_by(&:my_function)#Assumerun'my_function'haveresult1onelement1,element3andresult2onelement2,element4,then:#grouped_array={#result1=>[element1,element3],#result2=>[element2,el

  5. ruby-on-rails - 验证事件连接!在 Rails 4 中已弃用,我们应该如何处理该功能? - 2

    我一直在关注这篇文章以与工头一起设置puma:https://www.digitalocean.com/community/articles/how-to-set-up-zero-downtime-rails-deploys-using-puma-and-foremanpuma脚本在连接后告诉verify_active_connections!但它在rails4中不可用。注释掉方法调用将使脚本运行但我不确定这是否会泄漏资源.关于这个问题,我能看到的唯一文档是:https://github.com/socialcast/resque-ensure-connected/issues/3但是

  6. ruby - 带 compass 的 ruby 弃用警告 - 2

    当我尝试像往常一样在项目上运行“bundleexeccompasswatch”时,我现在收到此警告:DEPRECATIONWARNINGonline87of/home/hedy/Sites/mywebsite.fr/src/vendor/bundle/ruby/2.3.0/gems/compass-core-1.0.3/stylesheets/compass/css3/_deprecated-support.scss:#{}interpolationnearoperatorswillbesimplifiedinafutureversionofSass.Topreservethecurr

  7. ruby-on-rails - 弃用警告 : Dangerous query method (method whose arguments are used as raw SQL) called with non-attribute argument(s) - 2

    我将我的Rails5.1.4应用更新到了5.2.0。我的一个模型中有以下范围:scope:by_category,lambda{|category_slug|category_ids=Category.find_by(slug:category_slug)&.subtree_idswhere(category_id:category_ids)}由于该范围,Rails返回以下错误:DEPRECATIONWARNING:Dangerousquerymethod(methodwhoseargumentsareusedasrawSQL)calledwithnon-attributeargume

  8. ruby-on-rails - 这种弃用方法如何工作? - 2

    我试图理解这个调用:deprecate:new_record?,:new?它使用了这个弃用方法:defdeprecate(old_method,new_method)class_eval我不太了解这里使用的元编程。但是,这只是别名new_record?方法的另一种方式吗-所以实际上,new_record?仍然可用,但在您使用它时会发出警告?有人愿意解释一下这是如何工作的吗? 最佳答案 好的,所以这里发生的是old_method的所有功能都已被程序员移至new_method。为了使两个名称都指向相同的功能但注意弃用,程序员放入了dep

  9. ruby-on-rails - Ruby 2.4.1 - 警告:constant::Fixnum 已弃用 - 2

    这个问题在这里已经有了答案:Ruby2.4andRails4stackleveltoodeep(SystemStackError)(3个答案)关闭5年前。我是StackOverflow和Rails的新手,所以我希望这不是一个太幼稚的问题。我正在尝试使用bin/rails服务器在本地运行我的应用程序。当我输入时,我收到以下跟踪信息:=>BootingPuma=>Rails4.2.5applicationstartingindevelopmentonhttp://localhost:3000=>Run`railsserver-h`formorestartupoptions=>Ctrl-Ct

  10. ruby-on-rails - Rails 服务器无法启动,Rails 5 中的弃用警告(MIME?Sprockets?) - 2

    我使用“railss”,但服务器无法启动。我也是刚开始当我重新启动它时,我得到了这个:=>BootingPuma=>Rails5.0.0applicationstartingindevelopmentonhttp://localhost:3000=>Run`railsserver-h`formorestartupoptionsDEPRECATIONWARNING:Sprocketsmethod`register_engine`isdeprecated.Pleaseregisteramimetypeusing`register_mime_type`thenuse`register_com

随机推荐