自定义TextView导入外部特殊字体

来源:互联网 发布:java中的网络编程 编辑:程序博客网 时间:2024/05/22 03:31

前段时间由于项目需求,app需要使用特殊字体,所以在网上搜刮了一大波博客把需求完成了,但是由于并没有完美的解决问题(问题见上篇博客),几经曲折跟好基友请教了一番,毛瑟顿开,才有了一下这篇博文。
特殊字体包的导入请见上篇文章,这里就不在赘述了。接下来贴代码:


先是自定义一个textview为了接下来存放外部特殊字体,文件目录如下:
这里写图片描述

CustomTextView类文件:

package com.example.administrator.customview;import android.content.Context;import android.util.AttributeSet;import android.widget.TextView;/** * Created by Administrator on 2016-06-02. * 自定义 TextView */public class CustomTextView extends TextView {    public CustomTextView(Context context) {        super(context);        init(context);    }    public CustomTextView(Context context, AttributeSet attrs) {        super(context, attrs);        init(context);    }    public CustomTextView(Context context, AttributeSet attrs, int defSyle) {        super(context, attrs, defSyle);        init(context);    }    /***     * 设置字体     *     * @return     */    public void init(Context context) {        setTypeface(FontCustom.setFont(context));    }}

FontCustom类文件:

package com.example.administrator.customview;import android.content.Context;import android.graphics.Typeface;/** * Created by Administrator on 2016-06-02. * 特殊字体定义 */public class FontCustom {    static String fongUrl = "font/FangZhen_GBK.ttf";    static Typeface tf;    /***     * 设置字体     *     * @return     */    public static Typeface setFont(Context context) {        if(tf==null){            tf = Typeface.createFromAsset(context.getAssets(), fongUrl);        }        return tf;    }}

ok,自定义textview完成,接下来就是在xml布局里边调用,直接改变TextView标签就可以了:

 <customview.CustomTextView         android:id="@+id/UserCenter_txt"         android:layout_width="wrap_content"         android:layout_height="match_parent"         android:layout_marginTop="2dp"         android:layout_weight="6"         android:text="@string/UserCenter_txt"         />

完成了这些操作以后,就可以运行你的项目看看效果了,不用像上篇博客一样一个一个TextView控件去stetType()了,(笑哭……)!

运行后的效果图:
这里写图片描述

是不是完美解决了,系统字体字号过大就变粗的硬伤。

1 0