Android app设置字体大小和字体样式不随系统设置改变而改变

字体大小

在BaseActivity和BaseApplication里重写方法或者在基类里重写方法:

/设置字体为默认大小,不随系统字体大小改而改变
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        if (newConfig.fontScale != 1)//非默认值
            getResources();
        super.onConfigurationChanged(newConfig);
    }
 
 
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        if (res.getConfiguration().fontScale != 1) {//非默认值
            Configuration newConfig = new Configuration();
            newConfig.setToDefaults();//设置默认
            res.updateConfiguration(newConfig, res.getDisplayMetrics());
        }
        return res;
    }

字体样式

使用批量设置字体框架 Calligraphy

在build.gradle文件中添加:

implementation 'uk.co.chrisjenx:calligraphy:2.3.0'//设置字体样式

1.首先要在自己定义的Appliction类中的OnCreate方法中添加如下语句

//设置字体样式
		CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
//				.setDefaultFontPath("fonts/FZSong.ttf")
				.setDefaultFontPath("fonts/Roboto-Regular.ttf")
				.setFontAttrId(R.attr.fontPath)
				.addCustomViewWithSetTypeface(CustomViewWithTypefaceSupport.class)
				.addCustomStyle(TextField.class, R.attr.textFieldStyle)
				.build()
		);

2.定义一个BaseActivity类,所有的Activity都继承该类,然后添加如下方法(复写的)

//设置字体样式
	@Override
	protected void attachBaseContext(Context newBase) {
		super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
	}

3.把字体包是放在assets目录下的fonts文件夹下

4.在工程的build.gradle添加:

version = getProperty('VERSION_NAME')

    ext {
        isReleaseVersion = has("release")
        versionCodeInt = getProperty('VERSION_CODE').toInteger()
        supportLibraryVersion = '27.1.1'
        buildToolsVersion = '27.0.3'
        compileSdkVersion = 27
        minSdkVersion = 14
        targetSdkVersion = 27
    }

*考虑字体版权关系(方正和微软雅黑万万不能用会被追究起诉),字体使用时选择了思源黑体和思源宋体,思源字体确实好看可惜都会有行间距过大问题,下载的很多称修正版的都是假的,无奈只能舍弃,后来找到了一个破产公司fandol的字体也还不错,虽然最后领导没有采用(最后用的是“Roboto-Regular.ttf”)

最后附上一些字体,请见个人下载资源页面

思源黑体

思源宋体和fandol字体

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值