1.少量字体简单做法
下载字体文件.ttf,在项目main下面新建assets文件,将字体包导入,
然后在Activity中,调用,如下
Button button=findViewById(R.id.btn_handin);
// AssetManager assets = getAssets();//获取assets目录
// TextView textView1=findViewById(R.id.text_write);
// TextView textView = findViewById(R.id.text_type);
// Typeface fromAsset = Typeface.createFromAsset(assets, "boYangXingShu7000-1.ttf");//typeface字体文件
// button.setTypeface(fromAsset);
// textView1.setTypeface(fromAsset);
// textView.setTypeface(fromAsset);//设置字体类型
但是当我们需要改很多控件字体的时候,上面的方法就不太实用了,下面有更简单的方法
1.在grade文件下的dependencies中加入
//批量字体添加
implementation'uk.co.chrisjenx:calligraphy:2.2.0'
配置依赖路径,引入开源字体设置
2。在自定义的application的oncreate进行设置
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("boYangXingShu7000-1.ttf")
.setFontAttrId(R.attr.fontPath)
.build());
然后重写attachBaseContext方法,
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
最后就可以在布局文件中使用了,
<TextView
android:id="@+id/text_type"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:text="看看你适合的type"
fontPath="boYangXingShu7000-1.ttf"
android:textSize="25dp"
tools:ignore="MissingPrefix" />//因为上面的fontPath不识别,所以加这一行忽略前缀就好了