如何使用自定义字体在Android的XML? [英] How to use custom font in android xml?

查看:109
本文介绍了如何使用自定义字体在Android的XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用,我们增加了资产的文件夹中的XML自定义字体?我知道我们可以把这个用在Java setTypeface()方法,但我们必须处处做到这一点,我们使用Textview.So任何最好的方法?

How can i use the custom font which we add in asset folder in xml? i know we can use that using setTypeface() method in java but we have to do this everywhere where we use that Textview.So any best way?

推荐答案

我发现通过谷歌搜索是 - 说,如果你想在TextView中使用的话,我们已经延长了TextView的,并有后来设置字体在那最好的方法我们可以用我们的自定义的TextView在我们的XML。我会告诉下面

The best way i found by googling is- Say if you want to use in TextView then we have to extend the Textview and have to set the font in that later we can use our customised Textview in our xml. I'll show the extended TextView below

package com.vins.test;

import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;

public class MyTextView extends TextView {

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

    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MyTextView(Context context) {
        super(context);
        init();
    }

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

}

我们在调用init(),以在每个costructors的集字体。 后来我们不得不用这个在我们的main.xml中,如下图所示。

We calling init() to set font in each of the costructors. Later we have to use this in our main.xml as shown below.

<com.vins.test.MyTextView
    android:id="@+id/txt"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:layout_weight="1"
    android:text="This is a text view with the font u had set in MyTextView class "
    android:textSize="30dip"
    android:textColor="#ff0000"
   >

更新:

注意有关在pre-4.0的Andr​​oid的内存泄漏所提到的pandre。

Be aware about the memory leak in pre-4.0 Android as mentioned by pandre.

这篇关于如何使用自定义字体在Android的XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆