加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在 XML 中通过数据绑定用一行代码定制字体

发布时间:2020-12-16 08:53:17 所属栏目:百科 来源:网络整理
导读:在 XML 中通过数据绑定用一行代码定制字体 (plus.google.com) Lisa Wray 对新的数据绑定库的能力印象深刻,会在本文中展示如何用它来定制字体 I started playing with data binding last night for real,and I'm amazed by the power it gives you. Check
在 XML 中通过数据绑定用一行代码定制字体 (plus.google.com)

Lisa Wray 对新的数据绑定库的能力印象深刻,会在本文中展示如何用它来定制字体


I started playing with data binding last night for real,and I'm amazed by the power it gives you. Check out this one-liner to set a custom font on a TextView:

@BindingAdapter({"bind:font"})
public static void setFont(TextView textView,String fontName){

textView.setTypeface(Typeface.createFromAsset(textView.getContext().getAssets(),"fonts/" + fontName));
}
In XML:
<TextView
app:font="@{`Source-Sans-Pro-Regular.ttf`}"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Previously,this used to take endless lines of repetitive Java code (one for each TextView!). The missing custom typeface support in TextView has been a grievance held against the Android platform foryears. There's even an inventive library to address it[2]. Data binding makes all of that obselete. If you can't tell,I'm in love!! It's terse,powerful,and one of the biggest leaps forward I've seen for Android productivity.
As usual,you need to put your font file in assets/fonts/,and make sure to include the data binding framework. And if you're doing this to many TextViews,just get a little more fancy and cache the Typeface instead of creating it every time (thanks for the reminder+Ian Lake!)
[1]https://developer.android.com/tools/data-binding/guide.html
[2] Calligraphy:https://github.com/chrisjenx/Calligraphy?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读