Android中快速实现自定义字体!

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

开发环境:

Android Studio 2.2.2

compileSdkVersion 25

buildToolsVersion "25.0.0"

minSdkVersion 19

targetSdkVersion 25

compile 'com.android.support:appcompat-v7:25.0.0'

提示:使用项目时注意开发环境的更改,以免造成不必要的时间浪费。

1自定义字体

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

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

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

STXINGKA.TTF就是字体文件

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

public class FontCustom {
 
    // fongUrl是自定义字体分类的名称
    private static String fongUrl = "STXINGKA.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个参数的构造方法

public class MyTextView extends TextView {
    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }
    /**
     * 初始化字体
     * @param context
     */
    private void init(Context context) {
        //设置字体样式
        setTypeface(FontCustom.setFont(context));
    }
}

2使用自定义字体类

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

com.example.fengjun.fontdiy.MyTextView

修改activity_main中的代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"    tools:context="com.example.fengjun.fontdiy.MainActivity">
 
    <com.example.fengjun.fontdiy.MyTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:layout_centerInParent="true"
        android:text="Hello!我是自定义字体" />

</RelativeLayout>

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

3总结

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

 项目下载地址:http://pan.baidu.com/s/1pLhKgbh

猜你喜欢

转载自www.cnblogs.com/zhujiabin/p/9365624.html