android 使用外部字体

在assets目录下再建一个fonts文件夹,将字体文件放到里面



单个使用时可以使用此方法:

private void myTypeFace(TextView text){

TypeFace face = TypeFace.createFromAsset(getAssets(),"fonts/HanYi.ttf");

text.setTypeFace(face);

}


如大面积使用或全局使用可再Application中先加载取到对应的TypeFace 

import android.app.Application;
import android.graphics.Typeface;

/**
 * 自定义application
 * Created by Administrator on 2017/9/19 0019.
 */

public class TApplication extends Application{

    public static Typeface textTypeface = null;

    @Override
    public void onCreate() {
        super.onCreate();
        textTypeface = Typeface.createFromAsset(getAssets(), "fonts/huawenxingkai.ttf");
    }
}
自定义textView:

/**
 * 设置字体
 * Created by Administrator on 2016/5/31 0031.
 */
public class MyFontTextView extends AppCompatTextView{
    private Context mContext=null;
    Typeface textTypeface =null;
    public MyFontTextView(Context context) {
        super(context);
        init(context);
    }

    public MyFontTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }
    public MyFontTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs,defStyle);
        init(context);
    }

    private void init(Context context) {
        if(mContext==null){
            this.mContext = context;
        }
        if(textTypeface ==null){
            textTypeface = TApplication.textTypeface;
        }
        this.setTypeface(textTypeface);
    }
}
布局文件中引用:

xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    tools:context="com.gaof.typefacedemo.MainActivity">

            android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="系统自带字体效果"
        android:textSize="20sp"
        android:layout_marginTop="10dp"/>
            android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="外部字体效果"
        android:textSize="20sp"
        android:layout_marginTop="10dp" />


运行后效果图:

android 使用外部字体_第1张图片

你可能感兴趣的:(android 使用外部字体)