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

写在前面

在Android应用开发中,由于客户或者个人的需要(谁叫Android默认的字体那么丑),所以需要配置不同的字体,而 Android 只能在 xml 中配置系统默认提供的四种字体,需要自定义的字体都需要在 Java 代码中配置。

总结一下以前自定义字体的方法

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

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

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

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

public class CustomTextView extends TextView {

        public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }

        public CustomTextView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        public CustomTextView(Context context) {
            super(context);
        }

        public void setTypeface(Typeface tf, int style) {
            if (style == Typeface.BOLD) {
                super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/CustomFont_Bold.ttf"));
            } else {
                super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/CustomFont.ttf"));
            }
        }
    }

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

3 . Calligraphy

这是一个开源库,地址是https://github.com/chrisjenx/Calligraphy ,在github上5000+star,感觉还是不错的,也从侧面说出自定义字体的需求量有多大。

那么接下来就讲重点了

如何使用DataBinding来进行字体的自定义呢?

TOO EASY,不用每次都去手写,也不需要自定义View

首先,打开DataBinding

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    defaultConfig {
        ···
    }
    buildTypes {
        ···
    }
    dataBinding {
        enabled = true
    }
}

再看结构

结构.png

在项目中的assets/fonts文件夹下加入了5种字体,然后在strings.xml中定义了字体的路径

<resources>
    ···
    <string name="notoSans_regular">fonts/NotoSans-Regular.ttf</string>
    <string name="notoSansui_boldItalic">fonts/NotoSansUI-BoldItalic.ttf</string>
    <string name="icomoon">fonts/icomoon.ttf</string>
    <string name="nutso2">fonts/Nutso2.otf</string>
    <string name="ruthie">fonts/Ruthie.ttf</string>
    ···
</resources>

而在layout的xml中只需要这么使用,那么便已经完成了8成了

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>

    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:gravity="center"
            android:text="Hello world"
            android:textSize="18sp"
            android:typeface="@{@string/nutso2}"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:gravity="center"
            android:textSize="18sp"
            android:text="Hello world"
            android:typeface="@{@string/notoSans_regular}"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:gravity="center"
            android:textSize="18sp"
            android:text="Hello world"
            android:typeface="@{@string/notoSansui_boldItalic}"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:gravity="center"
            android:text="Hello world"
            android:textSize="18sp"
            android:typeface="@{@string/icomoon}"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:gravity="center"
            android:text="Hello world"
            android:textSize="18sp"
            android:typeface="@{@string/ruthie}"/>
    </LinearLayout>
</layout>

而剩下的两成,一成在FontBinding文件

public class FontBinding {

    @BindingConversion
    public static Typeface convertStringToFace(String s){
        try {
            return Typeface.createFromAsset(FontApp.getInstance().getAssets(),s);
        }catch (Exception e){
            throw e;
        }
    }
}

这里定义了一个转换器,将xml文件中获取到的字符资源,转换成了一个Typeface

最后一成,只需要使用就好了

public class MainActivity extends AppCompatActivity {

    ActivityMainBinding mMainBinding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
    }
}

看一下截图,一起哈啤


截图.jpg

没了解过DataBinding的人可能不知道ActivityMainBinding是怎么来的,这是编译时生成的,在如下图所示的位置可以找到

路径.png

打开ActivityMainBinding可以看到这样的代码

            this.mboundView1.setTypeface(com.ditclear.sample.FontBinding.convertStringToFace(mboundView1.getResources().getString(R.string.nutso2)));
            this.mboundView2.setTypeface(com.ditclear.sample.FontBinding.convertStringToFace(mboundView2.getResources().getString(R.string.notoSans_regular)));
            this.mboundView3.setTypeface(com.ditclear.sample.FontBinding.convertStringToFace(mboundView3.getResources().getString(R.string.notoSansui_boldItalic)));
            this.mboundView4.setTypeface(com.ditclear.sample.FontBinding.convertStringToFace(mboundView4.getResources().getString(R.string.icomoon)));
            this.mboundView5.setTypeface(com.ditclear.sample.FontBinding.convertStringToFace(mboundView5.getResources().getString(R.string.ruthie)));

这些mboundViewX就是xml中的TextView,由于没写id,所以都是自动生成的名称,可以看到给每一个使用了绑定的TextView都设置了字体,相当于系统帮我们做了第一个方法中重复性的工作。

当然我们还可以优化一下,由于每次都要操作assests文件夹,也会带来一定的开销,所以也有必要提供一个字体缓存FontCache,代码来自 britzl on stackoverflow

public class FontCache {

    private static ArrayMap<String, Typeface> fontCache = new ArrayMap<String, Typeface>();

    public static Typeface getTypeface(String fontName, Context context) {
        Typeface tf = fontCache.get(fontName);
        if(tf == null) {
            try {
                tf = Typeface.createFromAsset(context.getAssets(), fontName);
            }
            catch (Exception e) {
                return null;
            }
            fontCache.put(fontName, tf);
        }
        return tf;
    }
}

那么FontBinding就变成了这样

public class FontBinding {

    @BindingConversion
    public static Typeface convertStringToFace(String fontName){
        try {
            return FontCache.getTypeface(fontName,FontApp.getInstance());
        }catch (Exception e){
            throw e;
        }
    }

}

好了,大功告成!这也算是一种新思路吧。
附上github地址:https://github.com/ditclear/FontDataBinding

补充:
如果不想每次都在xml中设置字体,可以在绑定一个常用的属性时设置一个默认的字体。比如字体是需要作用在text上的,那么我们只需要在setText的时候绑定一个默认的字体就👌了,看代码

  public class FontBinding {
    ···
    @BindingAdapter("android:text")
    public static void setText(TextView v, String s){
        v.setTypeface(convertStringToFace(FontApp.getInstance().getString(R.string.ruthie)));
        v.setText(s);
    }
}

这样在绑定文本的时候就会绑定一个默认的字体,不用每次都写

  <?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>

    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center">

        <!--绑定默认字体-->
        <TextView
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:gravity="center"
            android:text="@{@string/hello_world}"
            android:textSize="18sp"/>
        <!--绑定默认字体,然后自定义字体-->
        <TextView
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:gravity="center"
            android:textSize="18sp"
            android:text="@{@string/hello_world}"
            android:typeface="@{@string/notoSans_regular}"/>

        ···
    </LinearLayout>
</layout>

最后,效果图:

默认字体.jpg

总结

这只是DataBinding的一个小例子,它能做的远不止如此,而且DataBinding是一个support库,最低支持到Android 2.1(API Level 7+)。不需要引入第三方库,只需要在app.build文件中开启就好了,而且学习成本极低。
再说明一个可能被大家误解的地方,DataBinding并不是要一定和MVVM结合使用,应该说是MVVM离不开DataBinding,但DataBinding是可以在其它任何框架下使用的,包括MVC、MVP等等,至少它可以取代ButterKnife,不用生成那么一长串@BindView的代码。

想要了解DataBinding的可以看看慕课网上的视频或者看看完全掌握Android Data Binding

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容