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);
    }
}
布局文件中引用:

<LinearLayout 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">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="系统自带字体效果"
        android:textSize="20sp"
        android:layout_marginTop="10dp"/>
    <com.gaof.typefacedemo.view.MyFontTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="外部字体效果"
        android:textSize="20sp"
        android:layout_marginTop="10dp" />

</LinearLayout>
运行后效果图:


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值