Android中字体设置和calligraphy(高效加载字体包)用法

Android默认字体

TextView 的 typeface 属性支持 “Sans”,”serif”,”monospace” 这三种字体,如果在没有指定字体的情况下,系统缺省会使用 “Sans” 作为文本显示的字体。但这三种字体只支持英文,也就是说只要你显示的文字是中文,无论你选择这三种字体中的哪一种,显示效果都是一样的

xml

<!--  使用默认的sans字体-->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/sans"
                 android:text="Hello,World"
                 android:typeface="sans"
                 android:textSize="20sp" />

    <!--  使用默认的serifs字体-->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/serif"
                android:text="Hello,World"
                android:typeface="serif"
                android:textSize="20sp" />

    <!--  使用默认的monospace字体-->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/monospace"
                android:text="Hello,World"
                android:typeface="monospace"
                android:textSize="20sp" />
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

效果

这里写图片描述

Android中可以引入其他字体

首先要将字体文件保存在assets/fonts/目录下

Android Studio如何添加assets文件夹

关键代码

Typeface typeFace =Typeface.createFromAsset(getAssets(),"fonts/default.ttf");
textView.setTypeface(typeFace);
  • 1
  • 2

calligraphy(高效加载字体包)

1、添加依赖

compile ‘uk.co.chrisjenx:calligraphy:2.3.0’

2、添加字体

这里写图片描述

扫描二维码关注公众号,回复: 1055008 查看本文章

3、安装

在自己定义的Appliction类中的OnCreate方法中添加如下语句

@Override
public void onCreate() {
    super.onCreate();
    CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
                            .setDefaultFontPath("fonts/Roboto-RobotoRegular.ttf")
                            .setFontAttrId(R.attr.fontPath)
                            .build()
            );
    //....
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

4、定义一个BaseActivity类,所有的Activity都继承该类,然后添加如下方法(复写的)

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
    }
  • 1
  • 2
  • 3
  • 4

5、用法

   <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView2"
        android:text="Hello,World"
        android:textSize="20sp"
        fontPath="fonts/default.ttf"/>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

更多用法可以点击查看GitHub-Calligraphy


如果出现拒绝访问则clean project 或者是assets目录没有放对,正确的应该是放在main目录下

猜你喜欢

转载自blog.csdn.net/ltp_zy/article/details/80256338
今日推荐