具体方法

  • 将下载到的字体文件复制到 assets/font 文件夹下
  • 编写自定义 View

    示例代码

    ```java public class MyTextView extends AppCompatTextView {

    private static Hashtable fontCache = new Hashtable<>();

  1. public MyTextView(Context context, AttributeSet attrs, int defStyle) {
  2. super(context, attrs, defStyle);
  3. init();
  4. }
  5. public MyTextView(Context context, AttributeSet attrs) {
  6. super(context, attrs);
  7. init();
  8. }
  9. public MyTextView(Context context) {
  10. super(context);
  11. init();
  12. }
  13. private void init() {
  14. if (!isInEditMode()) {
  15. Typeface tf = getTf();
  16. setTypeface(tf);
  17. }
  18. }
  19. public Typeface getTf() {
  20. String tag = "font/DIN-Regular.ttf";
  21. Typeface tf = fontCache.get(tag);
  22. if(tf == null) {
  23. try {
  24. tf = Typeface.createFromAsset(getContext().getAssets(), tag);
  25. } catch (Exception e) {
  26. return null;
  27. }
  28. fontCache.put(tag, tf);
  29. }
  30. return tf;
  31. }

}

```

示例图

image.png

字体提取工具

如果只引用第三方字体中的小部分,可使用此工具将引用部分提取到新的字体文件中,可优化加载字体文件大小
https://gitee.com/YpwCode/FontZip