Android使用字体文件犯的错误

项目中需要使用自定义的字体文件,于是想自定义一个方便使用,结果没注意犯了一个低级错误。

记录下来警醒下自己。

public class PingFangTextView extends TextView {

    public PingFangTextView(Context context) {
        this(context, null);
    }
    public PingFangTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public PingFangTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "PingFang.ttf");
        setTypeface(tf);
    }
}

这样写大家有发现问题吗?

如果在列表中使用,会导致列表滑动很卡,原因是下面这段代码导致的。

Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "PingFang.ttf");

Typeface.createFromAsset 该方法应该是需要读取文件,所以导致卡顿。

看源码,具体的代码在navtive里,有知道的可以帮忙发出来。

实际只要创建一个全局的对象,所有TextView使用即可。

public class GeoApp extends Application {
    private Typeface mPingFangTf;
    private static WeakReference<GeoApp> instance;
	
	@Override
	public void onCreate() {
		super.onCreate();
		instance = new WeakReference<GeoApp>(this);
	}
	
	public static GeoApp getApplicaton() {
		return instance.get();
	}

	public Typeface getPingFang() {
		if (mPingFangTf == null) {
			mPingFangTf = Typeface.createFromAsset(getAssets(), "PingFang.ttf");
		}
		return mPingFangTf;
	}
}
public class PingFangTextView extends TextView {
    public PingFangTextView(Context context) {
        this(context, null);
    }
    public PingFangTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public PingFangTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }
    private void init() {
        setTypeface(GeoApp.getApplicaton().getPingFang());
    }
}

 

转载于:https://my.oschina.net/android520/blog/805032

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值