0
点赞
收藏
分享

微信扫一扫

Android自定义字体

文章目的:快速入门Android中自定义各种字体!

前言:我们都知道,Android中默认的字体是黑体,而大多数app也都是使用的这种字体,但我们发现,大多数app中,个别地方字体非常好看,例如app的标题栏,菜单栏等地方,那他们是怎么做到的呢?有两种方式,第一是图片来代替文字,第二,就是今天我要教大家的自定义字体。

一 自定义字体

说到字体,我们不难联想到我们使用office时可以选择的各种字体,我们就是需要这种字体文件,值得一提的是,Windows提供了很多字体文件,可以在C:\Windows\Fonts找到。当然,我们也可以去网络上下载你喜欢的字体文件。字体文件是ttf格式的哟。

那我们现在就开始,我们先把要使用的字体文件放入到工具中,操作如下:

(1)新建一个名叫assets的文件夹,然后把字体文件复制到里面


Mogra-Regular.ttf就是字体文件

(2)我们新建一个类,名叫FontCustom,写入代码:

import android.content.Context;
import android.graphics.Typeface;

/**
 * author : i小灰
 * desc   :自定义字体
 */
public class FontCustom {

    // fongUrl是自定义字体分类的名称
    private static String fongUrl = "Mogra-Regular.ttf";
    //Typeface是字体,这里我们创建一个对象
    private static Typeface tf;

    /**
     * 设置字体
     */
    public static Typeface setFont(Context context)
    {
        if (tf == null)
        {
            //给它设置你传入的自定义字体文件,再返回回来
            tf = Typeface.createFromAsset(context.getAssets(),fongUrl);
        }
        return tf;
    }
}

(3)新建一个类名叫MyTextView继承TextView,重写2个参数的构造方法

import android.content.Context;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatTextView;

/**
 * author : i小灰
 * desc   :自定义字体
 */
public class MyTextView extends AppCompatTextView {
    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }
    /**
     * 初始化字体
     * @param context
     */
    private void init(Context context) {
        //设置字体样式
        setTypeface(FontCustom.setFont(context));
    }
}

使用自定义字体类

我们复制MyTextView的路径到activity_main中,替换原有的TextView,我这里的路径是
com.my.customfont.font.MyTextView

修改activity_main中的代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:gravity="center"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.my.customfont.font.MyTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello 我是i小灰!"
        android:textSize="25sp" />

</LinearLayout>

好了,到这里,我们就完成了自定义字体,现在我们运行程序看看效果!

效果很酷炫,对不对?我们只需要2个类就可以完成了自定义字体,之后再哪里需要使用自定义字体,就把路径替换原有的TextView就完成了!

字体地址

总结:
自定义字体在我们的程序中其实用的地方不多,大多数时候,我们都喜欢用图片来代替TextView来作为标题名称等特殊地方。如果我们在程序中展示的文字内容,使用自定义字体,那就是非常棒的选择,会给人一种耳目一新的感觉。

项目下载地址:https://pan.baidu.com/s/1Av_64Xz3z2Uf6BWPiNS3yw 提取码:1234
分享一个flutter项目,作为学习 OpenJMU

欢迎关注 i小灰 带你学习新知识!

举报

相关推荐

0 条评论