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字体

猜你喜欢

转载自blog.csdn.net/P876643136/article/details/91977725
今日推荐