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

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

问题描述

如何使用在我的 xml 的资产文件夹中添加的自定义字体?我知道我们可以在 java 中使用 setTypeface() 方法,但是我们必须在使用该 TextView 的任何地方都这样做.那么有没有更好的办法呢?

How can I use a custom font which was added in the asset folder in my xml? I know we can use setTypeface() method in java, but we have to do this everywhere where we use that TextView. So is there a better way?

推荐答案

我通过谷歌搜索找到的最好方法是 - 如果你想在 TextView 中使用,那么我们必须扩展 Textview 并且必须稍后设置字体我们可以在我们的 xml 中使用我们自定义的 Textview.我将在下面显示扩展的 TextView

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() 来设置每个构造函数中的字体.稍后我们必须在我们的 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"
   >

更新:

请注意 pandre 提到的 4.0 之前的 Android 中的内存泄漏.

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

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

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