通过xml设置自定义字体

时间:2012-07-13 13:39:59

标签: android xml fonts

如何通过xml设置一个字体,其ttf位于我的assets文件夹中? 我知道how to do that programmatically但你怎么能通过xml做到这一点?提前谢谢。

5 个答案:

答案 0 :(得分:14)

您无法直接使用XML,但您可以扩展TextView并设置默认字体。

package com.nannu;

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

public class NanTV extends TextView{

    private Context c;
    public NanTV(Context c) {
        super(c);
        this.c = c;
        Typeface tfs = Typeface.createFromAsset(c.getAssets(),
                "font/yourfont.ttf");
        setTypeface(tfs);

    }
    public NanTV(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.c = context;
        Typeface tfs = Typeface.createFromAsset(c.getAssets(),
                "font/yourfont.ttf");
        setTypeface(tfs);
        // TODO Auto-generated constructor stub
    }

    public NanTV(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.c = context;
        Typeface tfs = Typeface.createFromAsset(c.getAssets(),
                "font/yourfont.ttf");
        setTypeface(tfs);

    }


}

在您的布局中使用新的TextView

<com.nannu.NanTV
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" 

        />

我是根据我的热门答案https://stackoverflow.com/a/11239305/1166537

发布的

答案 1 :(得分:3)

如果您创建自己的TextView派生,则可以添加该类处理程序化方式的XML属性。这样,你指定一个特定的字体,它将被设置为运行时,但你通过XML来实现。 :)

否则,没有已知的方法来实现所请求的行为。

答案 2 :(得分:1)

您可以通过编写自定义TextView来执行此操作,否则您必须以编程方式设置它。有关详细信息,请参阅此link

答案 3 :(得分:1)

我在这里创建了一个库来解决这个问题:http://responsiveandroid.com/2012/03/15/custom-fonts-in-android-widgets.html

扩展TextView并在xml中设置字体的名称。有一个可下载的样本。

答案 4 :(得分:0)

You can include custom fonts under assets/fonts and then using the code from https://github.com/browep/AndroidCustomFontWidgets/

您可以在XML中指定字体,例如

<com.github.browep.customfonts.view.FontableTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="This is in a custom font"
        app:font="MyFont-Bold.otf" />

代码支持FontableTextView和FontableButton,但如果需要,它可以很容易地扩展以支持其他小部件类型。