使用xml在Android TextView中使用自定义字体

时间:2012-02-17 11:02:33

标签: java android xml android-layout fonts

我已将自定义字体文件添加到我的assets / fonts文件夹中。如何从我的XML中使用它?

我可以从代码中使用它,如下所示:

TextView text = (TextView) findViewById(R.id.textview03);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/Molot.otf");
text.setTypeface(tf);

我不能使用android:typeface="/fonts/Molot.otf"属性从XML中执行此操作吗?

11 个答案:

答案 0 :(得分:44)

简短回答:不会.Android没有内置支持通过XML将自定义字体应用于文本小部件。

但是,有一种解决方法实施起来并不是非常困难。

<强>第一

您需要定义自己的样式。在/ res / values文件夹中,打开/创建attrs.xml文件并添加一个声明样式的对象,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="FontText">
        <attr name="typefaceAsset" format="string"/>
    </declare-styleable>
</resources>

<强>第二

假设您经常要使用此窗口小部件,则应为加载的Typeface对象设置一个简单缓存,因为动态加载它们可能需要一些时间。类似的东西:

public class FontManager {
    private static FontManager instance;

    private AssetManager mgr;

    private Map<String, Typeface> fonts;

    private FontManager(AssetManager _mgr) {
        mgr = _mgr;
        fonts = new HashMap<String, Typeface>();
    }

    public static void init(AssetManager mgr) {
        instance = new FontManager(mgr);
    }

    public static FontManager getInstance() {
        if (instance == null) {
            // App.getContext() is just one way to get a Context here
            // getContext() is just a method in an Application subclass
            // that returns the application context
            AssetManager assetManager = App.getContext().getAssets();
            init(assetManager);
        }
        return instance;
    }

    public Typeface getFont(String asset) {
        if (fonts.containsKey(asset))
            return fonts.get(asset);

        Typeface font = null;

        try {
            font = Typeface.createFromAsset(mgr, asset);
            fonts.put(asset, font);
        } catch (Exception e) {

        }

        if (font == null) {
            try {
                String fixedAsset = fixAssetFilename(asset);
                font = Typeface.createFromAsset(mgr, fixedAsset);
                fonts.put(asset, font);
                fonts.put(fixedAsset, font);
            } catch (Exception e) {

            }
        }

        return font;
    }

    private String fixAssetFilename(String asset) {
        // Empty font filename?
        // Just return it. We can't help.
        if (TextUtils.isEmpty(asset))
            return asset;

        // Make sure that the font ends in '.ttf' or '.ttc'
        if ((!asset.endsWith(".ttf")) && (!asset.endsWith(".ttc")))
            asset = String.format("%s.ttf", asset);

        return asset;
    }
}

这个允许你使用.ttc文件扩展名,但它没有经过测试。

<强>第三

创建一个子类TextView的新类。此特定示例考虑了已定义的XML字体(bolditalic等)并将其应用于字体(假设您使用的是.ttc文件)。

/**
 * TextView subclass which allows the user to define a truetype font file to use as the view's typeface.
 */
public class FontText extends TextView {
    public FontText(Context context) {
        this(context, null);
    }

    public FontText(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FontText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        if (isInEditMode())
            return;

        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.FontText);

        if (ta != null) {
            String fontAsset = ta.getString(R.styleable.FontText_typefaceAsset);

            if (!TextUtils.isEmpty(fontAsset)) {
                Typeface tf = FontManager.getInstance().getFont(fontAsset);
                int style = Typeface.NORMAL;
                float size = getTextSize();

                if (getTypeface() != null)
                    style = getTypeface().getStyle();

                if (tf != null)
                    setTypeface(tf, style);
                else
                    Log.d("FontText", String.format("Could not create a font from asset: %s", fontAsset));
            }
        }
    }
}

<强>最后

使用完全限定的类名替换XML中TextView的实例。像Android命名空间一样声明自定义命名空间。请注意,“typefaceAsset”应指向/ assets目录中包含的.ttf或.ttc文件。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.example.FontText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is a custom font text"
        custom:typefaceAsset="fonts/AvenirNext-Regular.ttf"/>
</RelativeLayout>

答案 1 :(得分:27)

以下是执行此操作的示例代码。我在静态最终变量中定义了字体,字体文件在assets目录中。

public class TextViewWithFont extends TextView {

    public TextViewWithFont(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.setTypeface(MainActivity.typeface);
    }

    public TextViewWithFont(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.setTypeface(MainActivity.typeface);
    }

    public TextViewWithFont(Context context) {
        super(context);
        this.setTypeface(MainActivity.typeface);
    }

}

答案 2 :(得分:13)

创建属于您要使用的字体的自定义TextView。在这个类中,我使用静态mTypeface字段来缓存Typeface(为了更好的性能)

public class HeliVnTextView extends TextView {

/*
 * Caches typefaces based on their file path and name, so that they don't have to be created every time when they are referenced.
 */
private static Typeface mTypeface;

public HeliVnTextView(final Context context) {
    this(context, null);
}

public HeliVnTextView(final Context context, final AttributeSet attrs) {
    this(context, attrs, 0);
}

public HeliVnTextView(final Context context, final AttributeSet attrs, final int defStyle) {
    super(context, attrs, defStyle);

     if (mTypeface == null) {
         mTypeface = Typeface.createFromAsset(context.getAssets(), "HelveticaiDesignVnLt.ttf");
     }
     setTypeface(mTypeface);
}

}

在xml文件中:

<java.example.HeliVnTextView
        android:id="@+id/textView1"
        android:layout_width="0dp"
        ... />

在java类中:

HeliVnTextView title = new HeliVnTextView(getActivity());
title.setText(issue.getName());

答案 3 :(得分:11)

Activity实现了LayoutInflater.Factory2,它为每个创建的View提供回调。 可以使用自定义字体Family属性设置TextView的样式,根据需要加载字体并自动在实例化的文本视图上调用setTypeface。

不幸的是,由于Inflater实例相对于Activities和Windows的架构关系,在android中使用自定义字体的最简单方法是在应用程序级别缓存加载的字体。

示例代码库位于:

https://github.com/leok7v/android-textview-custom-fonts

  <style name="Baroque" parent="@android:style/TextAppearance.Medium">
    <item name="android:layout_width">fill_parent</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:textColor">#F2BAD0</item>
    <item name="android:textSize">14pt</item>
    <item name="fontFamily">baroque_script</item>
  </style>

  <?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:custom="http://schemas.android.com/apk/res/custom.fonts"
          android:orientation="vertical"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
  >
  <TextView
    style="@style/Baroque"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/sample_text"
  />

结果

enter image description here

答案 4 :(得分:7)

由于this fact而在xml中使用自定义字体不是一个好主意 也就是说,你必须以编程方式进行以避免内存泄漏!

答案 5 :(得分:7)

  

更新:https://github.com/chrisjenx/Calligraphy似乎是一个   对此有很好的解决方案。

创建应用程序时,也许你可以使用反射将字体注入/破解可用字体的静态列表?我感兴趣的是其他人的反馈,如果这是真的,非常糟糕的主意或者这是一个伟大的解决方案 - 它似乎将成为其中一个极端。 ..

我能够将自定义字体注入到具有我自己的字体系列名称的系统字体列表中,然后将该自定义字体系列名称(“brush-script”)指定为标准android:FontFamily的值TextView适用于运行Android 6.0的LG G4。

public class MyApplication extends android.app.Application
{
    @Override
    public void onCreate()
    {
        super.onCreate();

        Typeface font = Typeface.createFromAsset(this.getResources().getAssets(),"fonts/brush-script.ttf");
        injectTypeface("brush-script", font);
    }

    private boolean injectTypeface(String fontFamily, Typeface typeface)
    {
        try
        {
            Field field = Typeface.class.getDeclaredField("sSystemFontMap");
            field.setAccessible(true);
            Object fieldValue = field.get(null);
            Map<String, Typeface> map = (Map<String, Typeface>) fieldValue;
            map.put(fontFamily, typeface);
            return true;
        }
        catch (Exception e)
        {
            Log.e("Font-Injection", "Failed to inject typeface.", e);
        }
        return false;
    }
}

在我的布局中

<TextView
    android:id="@+id/name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Fancy Text"
    android:fontFamily="brush-script"/>

答案 6 :(得分:3)

  

在资源中创建一个字体文件夹,并在那里添加所需的所有字体。

public class CustomTextView extends TextView {
    private static final String TAG = "TextView";

    public CustomTextView(Context context) {
        super(context);
    }

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

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

    private void setCustomFont(Context ctx, AttributeSet attrs) {
        TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.CustomTextView);
        String customFont = a.getString(R.styleable.CustomTextView_customFont);
        setCustomFont(ctx, customFont);
        a.recycle();
    }

    public boolean setCustomFont(Context ctx, String fontName) {
        Typeface typeface = null;
        try {
            if(fontName == null){
                fontName = Constants.DEFAULT_FONT_NAME;
            }
            typeface = Typeface.createFromAsset(ctx.getAssets(), "fonts/" + fontName);
        } catch (Exception e) {
            Log.e(TAG, "Unable to load typeface: "+e.getMessage());
            return false;
        }
        setTypeface(typeface);
        return true;
    }
}

并在 attrs.xml

中添加声明
<declare-styleable name="CustomTextView">
      <attr name="customFont" format="string"/>
</declare-styleable>

然后添加你的customFont

app:customFont="arial.ttf"

答案 7 :(得分:3)

我知道这是一个老问题,但我找到了一个更容易的解决方案。

首先像往常一样在xml中声明TextView。 将您的字体(TTF或TTC)放在资产文件夹

  

应用\ SRC \主\资产\

然后在onCreate方法中设置文本视图的字体。

@Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_name);    

    TextView textView = findViewById(R.id.my_textView);
    Typeface typeface = Typeface.createFromAsset(getAssets(), "fontName.ttf");
    textView.setTypeface(typeface);
}

完成。

答案 8 :(得分:0)

而不是xmlns:custom =“schemas.android.com/tools”;你应该使用:xmlns:custom =“schemas.android.com/apk/res-auto”;为了使用可设置的属性。 我做了这个改变,现在正在运作。

答案 9 :(得分:0)

最好的解决方案是(最终)使用Google引入的XML自定义字体功能。但是您必须以API 26为目标。它支持API 16 +

https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml

答案 10 :(得分:0)

现在您可以在 XML 中设置字体而无需添加任何其他类的最新更新,例如:

android:fontFamily="@font_folder/font_file"