How to change the Font Size in a whole Application programmatically, Android?

后端 未结 6 1459
迷失自我
迷失自我 2020-11-29 05:49

I have created Spinner with the list of Font Sizes from \"8\" to \"46\" . I could be able to click the font Size and in a spinner it has shown me .

My need is, if i

6条回答
  •  眼角桃花
    2020-11-29 06:29

    To scale the font size of all components(mean whole application), there is pretty well approach which is implemented and tested trough several devices. This solution could be applied for cases like; declaring dp size unit statically(android sp by default) , scaling to desired font sizes and etc.

    The solution is similar to answer given by Usama Saeed US but will cover all buggy cases.

    Declare static util method which will scale font size.

        //LocaleConfigurationUtil.class
        public static Context adjustFontSize(Context context){
            Configuration configuration = context.getResources().getConfiguration();
            // This will apply to all text like -> Your given text size * fontScale
            configuration.fontScale = 1.0f;
    
            return context.createConfigurationContext(configuration);
        }
    

    In your all activities, override the attachBaseContext and call util method in onCreate.

       @Override
        protected void attachBaseContext(Context newBase) {
            super.attachBaseContext(LocaleConfigurationUtil.adjustFontSize(newBase));
        }
    
       @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            LocaleConfigurationUtil.adjustFontSize(this);
        }
    

    If you are using fragments then override onAttach method

    @Override
    public void onAttach(Context context) {
    super.onAttach(LocaleConfigurationUtil.adjustFontSize(context));
    }
    

提交回复
热议问题