Android O Working With Fonts

英文原版:Android O Working With Fonts
  Android O 首次引入一个新特性:允许开发者将字体作为资源在XML文件中使用。Android O同样提供了可以获取系统字体信息并生成文件描述的机制。
   Fonts in XML
  Android O允许开发者通过将font文件添加到res/font文件夹的方式绑定字体资源。这些字体会被编译进R文件中并且在Android Studio中自动生效。开发者可以通过使用@font/myfont或者 R.font.myfont的方式使用字体资源。
   在Android studio中通过下面的步骤将字体添加为资源:
   1.在res文件夹上右键,New > Android resource directory。
   2.在Resource type 列表中选择font,点击ok。
resource-directory-font
   3.将字体文件添加到font文件夹。下面的文件夹结果将生成R.font.dancing_script, R.font.lobster, and R.font.typo_graphica。

font-files-structure

  4.双击字体文件可以在编辑器中预览字体。
  Creating a font family 
  1.新建font resource文件,输入名字。
  2.打开新建的font文件,在每一个font节点中都写入字体文件(@font/my_font),weight和style:

<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
    <font
        android:fontStyle="normal"
        android:fontWeight="400"
        android:font="@font/lobster_regular" />
    <font
        android:fontStyle="italic"
        android:fontWeight="400"
        android:font="@font/lobster_italic" />
</font-family>

  Using fonts in XML layouts
  开发者可以很方便的在TextView或者styles中使用字体,在TextVie或者styles中使用字体需要fontFamily 属性。
  为TextView设置字体需要做下面的步骤:
  a.打开XML文件,使用fontFamily 属性调用字体文件:

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="@font/lobster"/>

  b.打开属性窗口为TestView设置字体:
  选择一个View打开属性窗口(属性窗口只有在design editor打开是才可用,开发者需要确保选择的是design editor)。
  展开textAppearance 属性,从fontFamily列表中选择字体。
property-window
  Android studio中的布局预览,开发者可用预览在TextView中设置的字体:
xml-font-preview
  Adding fonts to style
  打开styles.xml,使用fontFamily 属性引入字体文件:

<style name="customfontstyle" parent="@android:style/TextAppearance.Small">
    <item name="android:fontFamily">@font/lobster</item>
</style>

  Using fonts programmatically
  开发者可以通过使用getFont(int)方法获取字体信息,开发者需要将需要获取的字体资源的id传递给这个方法。getFont(int)方法返回一个Typeface对象。开发者可以使用Typeface.create(typeface, style)方法指导styles。

Typeface typeface = getResources().getFont(R.font.myfont);
textView.setTypeface(typeface);

   Retrieving system fonts
   fonts.xml文件记录了所有预装在设备中的字体和他们的细节,比如family name, weight, 和style。目前为止,Android还没有公共API去获取这些系统字体的数据。因此一些应用直接在fonts.xml文件中找到这些系统字体并将他们替换成自己的字体而不是使用他们。Android O提供了新的将fonts.xml文件中的信息公开的API,并且为这些字体文件提供了FileDescriptor对象。新的API是:

FontManager.getSystemFonts(): 提供与系统相关的字体信息,提供FileDescriptor
FontConfig: 包含所有和字体信息相关的数据结构

  Accessing APIs from your app
  通过下面的方法使用新的API:

FontManager fontManager = context.getSystemService(FontManager.class);
FontConfig systemFontsData = fontManager.getSystemFonts();
//FontConfig 类包含了所以定义在font families中的数据,对每一个在font families中的字体来说,他们的细节包括weight 和style。这个类同样提供了对字体文件的开放的file descriptor,一旦结束使用他们,调用者需要确保关闭给定的 file descriptors。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值