仅来自xml的自定义TrueType字体

时间:2011-12-07 10:09:09

标签: android true-type-fonts

有没有办法只使用xml传递TextView(或它的子类)的自定义字体,而不提供像这样的任何java代码

Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/CustomFont.ttf");

1 个答案:

答案 0 :(得分:5)

不可能完全来自XML ,但可以创建自定义视图并从XML引用它。这样,您只需编写一次代码,就可以以各种布局回收它。

例如,声明类FontTextView

package com.example;

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

public class FontTextView extends TextView {

    /** 
     *  Note that when generating the class from code, you will need
     *  to call setCustomFont() manually.
     */
    public FontTextView(Context context) {
        super(context);
    }

    public FontTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setCustomFont(this, attrs);
    }

    public FontTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setCustomFont(this, attrs);
    }

    private void setCustomFont(Context context, AttributeSet attrs) {
        if (isInEditMode()) {
            // Ignore if within Eclipse
            return;
        }
        String font = "myDefaultFont.ttf";
        if (attrs != null) {
            // Look up any layout-defined attributes
            TypedArray a = obtainStyledAttributes(attrs,
                    R.styleable.FontTextView);
            for (int i = 0; i < a.getIndexCount(); i++) {
                int attr = a.getIndex(i);
                switch (attr) {
                case R.styleable.FontTextView_customFont:
                    font = a.getString(attr, 0);
                    break;
                }
            }
            a.recycle();
        }
        Typeface tf = null;
        try {
            tf = Typeface.createFromAsset(getAssets(), font);
        } catch (Exception e) {
            Log.e("Could not get typeface: " + e.getMessage());
        }
        setTypeface(tf);
    }

}

res/values/attrs.xml中定义属性:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="FontTextView">
        <attr name="customFont" format="string" />
    </declare-styleable>

</resources>

在布局中使用它:

  1. 声明命名空间:

    xmlns:custom="http://schemas.android.com/apk/res/com.example"
    
  2. 使用FontTextView

    <com.example.FontTextView
        android:id="@+id/introduction"
        customFont="myCustomFont.ttf"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Hello world!" />
    
相关问题