Configuration `locale` variable is deprecated - Android

后端 未结 1 1602
不知归路
不知归路 2020-12-29 21:55

I use this code to set the default language manually in multiple languages app:

public static void setLanguage(Context context, String languageCode){
    Loc         


        
相关标签:
1条回答
  • 2020-12-29 22:52

    Hope this helps, I also added the getters.

    @SuppressWarnings("deprecation")
    public Locale getSystemLocaleLegacy(Configuration config){
        return config.locale;
    }
    
    @TargetApi(Build.VERSION_CODES.N)
    public Locale getSystemLocale(Configuration config){
        return config.getLocales().get(0);
    }
    
    @SuppressWarnings("deprecation")
    public void setSystemLocaleLegacy(Configuration config, Locale locale){
        config.locale = locale;
    }
    
    @TargetApi(Build.VERSION_CODES.N)
    public void setSystemLocale(Configuration config, Locale locale){
        config.setLocale(locale);
    }
    
    public static void setLanguage(Context context, String languageCode){
        Locale locale = new Locale(languageCode);
        Locale.setDefault(locale);
        Configuration config = new Configuration();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            setSystemLocale(config, locale);
        }else{
            setSystemLocaleLegacy(config, locale);
        }
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1)
            context.getApplicationContext().getResources().updateConfiguration(config,
                context.getResources().getDisplayMetrics());
    }
    

    UPDATE 12/3/2016

    Since context.getApplicationContext().getResources().updateConfiguration() is now deprecated, I highly recommend that you check out this solution and adopt a different approach to overwriting Android system configuration.

    Better Solution: https://stackoverflow.com/a/40704077/2199894

    0 讨论(0)
提交回复
热议问题