博观而约取,厚积而薄发。这篇文章主要讲述Android开发之字体设置相关的知识,希望能为你提供帮助。
默认字体android SDK自带了四种字体:"normal"“
monospace",“
sans”
, “
serif”
,如下:

文章图片
字体
看这四兄弟长的还是蛮像,我是看不出多大差别。。。
设置方式1.通过XML文件设置
< TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="monospace" android:textSize="20dp" android:textColor="#000000" android:typeface="monospace" android:layout_margin="5dp"/>
2.java代码中设置
TextView txtNormal = (TextView) findViewById(R.id.txt_normal); txtNormal.setTypeface(Typeface.MONOSPACE);
设置第三方字体 Res中使用
右键选择项目的app / res文件夹,然后选择New > Android resource directory。

文章图片
image.pngResource type中选择font,File name名为font。

文章图片
image.png【Android开发之字体设置】将字体文件拷贝到font中

文章图片
image.pngjava代码中使用
TextView txtNormal = (TextView) findViewById(R.id.txt_helvetica); Typeface typeface = ResourcesCompat.getFont(this, R.font.helvetica); txtNormal.setTypeface(typeface);
Assets中使用
新建Assets及fonts目录,并将字体文件拷贝到fonts目录下

文章图片
拷贝字体
在java代码中使用
TextView txtNormal = (TextView) findViewById(R.id.txt_helvetica); Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/helvetica.ttf"); txtNormal.setTypeface(typeface);
第三方框架全局字体设置这里推荐一个第三方字体设置库Calligraphy,详细可以点击连接
添加依赖
compile ‘uk.co.chrisjenx:calligraphy:2.3.0‘
新建Application
public class BaseApplication extends Application { @Override public void onCreate() { super.onCreate(); CalligraphyConfig.initDefault(new CalligraphyConfig.Builder() .setDefaultFontPath("fonts/Helvetica.ttf") .setFontAttrId(R.attr.fontPath) .build() ); } }
在Activity中重写attachBaseContext方法
@Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase)); }
在xml中使用
< TextView android:id="@+id/txt_helvetica" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Lorem ipsum" android:textSize="20dp" android:textColor="#000000" android:layout_margin="5dp" fontPath="fonts/Helvetica.ttf" tools:ignore="MissingPrefix"/>
如果fontPath="fonts/Helvetica.ttf"报错,在View上添加 tools:ignore="MissingPrefix” 即可。
其他具体功能,详见Calligraphy
推荐阅读
- @GetMapping和@PostMapping接收参数的格式
- [Android] Android 实现类似 今日头条 视频播放列表
- Android高版本联网失败报错:Cleartext HTTP traffic to xxx not permitted解决方法
- 6个针对NodeJS应用程序的最佳监视工具
- 选择React Native进行移动应用开发的7个理由
- Python数据分析的友好介绍
- Python脚本定期删除文件
- 每个开发人员都应了解的11个Python库和模块
- 11个很棒的iOS资源,使你成为更好的应用程序开发人员