使用DataBinding来进行字体的自定义

在Android开发中,自定义字体通常需要繁琐的操作。本文介绍了如何利用DataBinding库简化这一过程,无需手动设置或创建自定义View。通过DataBinding,可以方便地在assets/fonts目录下管理字体,并在XML布局中直接引用,结合转换器实现字体设置。编译时,DataBinding会自动为每个TextView设置字体,提高效率并减少资源消耗。同时,文章提到了字体缓存的实现,进一步优化性能。
摘要由CSDN通过智能技术生成

1 .通过findViewById找到view,然后一个个的去设置字体

 
 
 
  1. Typeface customFont = Typeface.createFromAsset(this.getAssets(), "fonts/customFont.ttf");
  2. TextView view = (TextView) findViewById(R.id.text);
  3. view.setTypeface(customFont);
  4. ···

一个看着还好,可是应用中可是有很多的文本或者按钮的,不可能逐个去设置。于是大多数都选择了第二种方法。

2 .创建一个子类,继承自TextView或者Button等等

 
 
 
  1. public class CustomTextView extends TextView {
  2. public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
  3. super(context, attrs, defStyle);
  4. }
  5. public CustomTextView(Context context, AttributeSet attrs) {
  6. super(context, attrs);
  7. }
  8. public CustomTextView(Context context) {
  9. super(context);
  10. }
  11. public void setTypeface(Typeface tf, int style) {
  12. if (style == Typeface.BOLD) {
  13. super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/CustomFont_Bold.ttf"));
  14. } else {
  15. super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/CustomFont.ttf"));
  16. }
  17. }
  18. }

然后在xml文件中每次都使用自定义的View,相比上一个方案,这一个要稍微好点。但相信都达不到各位的要求,只不过是换一个字体,需要这么麻烦吗?

3 . Calligraphy

这是一个开源库,地址是https://github.com/chrisjenx/Calligraphy ,在github上5000+star,感觉还是不错的,也从侧面

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值