How to use Calligraphy with multi-language support Oreo

前端 未结 3 1170
小蘑菇
小蘑菇 2021-01-03 04:14

I\'m developing an app that need to support multiple languages and if the language is RTL I have to apply a custom font. For the requirement I have created my Class that

3条回答
  •  南笙
    南笙 (楼主)
    2021-01-03 04:56

    @Override
    protected void attachBaseContext(Context newBase) {
        ContextWrapper localeContextWrapper = LocaleManager.wrap(newBase, "en");
        ContextWrapper calligraphyContextWrapper = CalligraphyContextWrapper.wrap(localeContextWrapper);
        super.attachBaseContext(calligraphyContextWrapper);
    }
    

    LocaleManager.java

    public class LocaleManager {
        public static ContextWrapper wrap(Context context, String language) {
            Resources res = context.getResources();
            Configuration configuration = res.getConfiguration();
            Locale newLocale = new Locale(language);
    
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                configuration.setLocale(newLocale);
                LocaleList localeList = new LocaleList(newLocale);
                LocaleList.setDefault(localeList);
                configuration.setLocales(localeList);
                context = context.createConfigurationContext(configuration);
    
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                configuration.setLocale(newLocale);
                context = context.createConfigurationContext(configuration);
    
            } else {
                configuration.locale = newLocale;
                res.updateConfiguration(configuration, res.getDisplayMetrics());
            }
    
            return new ContextWrapper(context);
        }
    }
    

提交回复
热议问题