Accessing a font under assets folder from XML file

2019-01-14 10:50发布

I am trying to do a application-wide font change and creating a style file to do so. In this file (below) I just want to change typeface value of TextAppearance style of Android.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="NightRiderFont" parent="@android:style/TextAppearance">
        <item name="android:typeface"> /***help need here***/ </item>
    </style>
</resources>

However font is in "assets/fonts/". How can I access this font, so I can use that style as a theme to get rid of changing all TextViews by hand programatically.

As summary: How can I access 'a file from assets folder' in XML?

13条回答
Deceive 欺骗
2楼-- · 2019-01-14 11:17

Soorya is right, but if you have to put the same font on many textViews, I recommend you to put that code inside a static method that return the Typeface wanted. It will reduce lines in your code. Or even better create a class that extends Application and make a GET method that return the Typeface. That method will be reachable from any Activity inside your application (without the need of using static variables or static methods).

查看更多
啃猪蹄的小仙女
3楼-- · 2019-01-14 11:18

Instead of assets folder, you can put the .ttf file on fonts folder. To use fonts support in XML feature on devices running Android 4.1 (API level 16) and higher, use the Support Library 26+. Right click res folder, new -> Android resource directory-> select font -> Ok. put your "myfont.ttf" file in newly created font folder.

On res/values/styles.xml add,

<style name="customfontstyle" parent="@android:style/TextAppearance.Small">
<item name="android:fontFamily">@font/myfont</item>
</style>

On layout file add android:textAppearance="@style/customfontstyle",

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="@style/customfontstyle"/>

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

查看更多
Summer. ? 凉城
4楼-- · 2019-01-14 11:20

I took droid kid's answer and made it work with ANY font, just by typing the font filename directly into the XML:

layout.xml

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

    <!-- where font file is at "assets/fonts/arial.ttf" -->
    <com.odbol.widgets.TextViewWithFont
        ...
        custom:fontFilePath="fonts/arial.ttf" />

</RelativeLayout>

Fonts.java

public class Fonts {

    // use Weak so fonts are freed from memory when you stop using them
    private final static Map<String, Typeface> fonts = new WeakHashMap<>(5);

    /***
     * Returns a font at the given path within the assets directory.
     *
     * Caches fonts to save resources.
     *
     * @param context
     * @param fontPath Path to a font file relative to the assets directory, e.g. "fonts/Arial.ttf"
     * @return
     */
    public synchronized static Typeface getFont(Context context, String fontPath) {
        Typeface font = fonts.get(fontPath);

        if (font == null) {
            font = Typeface.createFromAsset(context.getAssets(), fontPath);
            fonts.put(fontPath, font);
        }

        return font;
    }
}

values/attrs.xml

<resources>

    <declare-styleable name="TextViewWithFont">
        <!-- a path to a font, relative to the assets directory -->
        <attr name="fontFilePath" format="string" />

        <attr name="type">
            <enum name="bold" value="1"/>
            <enum name="italic" value="2"/>
        </attr>
    </declare-styleable>
</resources>

TextViewWithFont.java

public class TextViewWithFont extends TextView {
    private int defaultDimension = 0;
    private int TYPE_BOLD = 1;
    private int TYPE_ITALIC = 2;
    private int fontType;
    private int fontName;

    public TextViewWithFont(Context context) {
        super(context);
        init(null, 0);
    }
    public TextViewWithFont(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs, 0);
    }
    public TextViewWithFont(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs, defStyle);
    }
    private void init(AttributeSet attrs, int defStyle) {
        // Load attributes
        final TypedArray a = getContext().obtainStyledAttributes(
                attrs, R.styleable.TextViewWithFont, defStyle, 0);
        String fontPath = a.getString(R.styleable.TextViewWithFont_fontFilePath);
        fontType = a.getInt(R.styleable.TextViewWithFont_type, defaultDimension);
        a.recycle();

        if (fontPath != null) {
            setFontType(Fonts.getFont(getContext(), fontPath));
        }
    }
    private void setFontType(Typeface font) {
        if (fontType == TYPE_BOLD) {
            setTypeface(font, Typeface.BOLD);
        } else if (fontType == TYPE_ITALIC) {
            setTypeface(font, Typeface.ITALIC);
        } else {
            setTypeface(font);
        }
    }
}
查看更多
beautiful°
5楼-- · 2019-01-14 11:21

You can use this library: https://github.com/chrisjenx/Calligraphy

You only have to add the font you want to use on your layout. Like this:

<TextView
 fontPath="fonts/verdana.ttf"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"/>
查看更多
Bombasti
6楼-- · 2019-01-14 11:23

Edit 2:

Finally fonts are supported by xml (also backwards compatible via support library): https://developer.android.com/preview/features/fonts-in-xml.html


Edit:

I now use the Calligraphy library . It is the easiest way for custom fonts.

What can you do:

  • Custom font in a TextView
  • Custom font in TextAppearance
  • Custom font in Styles
  • Custom font in Themes
  • FontSpannable to only apply font to a part of the text

I found another way to do this.

You have to make your own TextView using this tutorial

It is not that difficult and after this you can just use that TextView with your own font.

I don't know if anybody still watches this, but I thought it might help.

查看更多
戒情不戒烟
7楼-- · 2019-01-14 11:24

In my research, there is no way to add external font to the xml file. Only the 3 default font is available in xml

But you can use in java using this code.

Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/verdana.ttf");  
textfield.setTypeface(tf,Typeface.BOLD);

Update:

Now I find a way to do this by creating a custom class extending the TextView and use that in the xml file.

public class TextViewWithFont extends TextView {
    private int defaultDimension = 0;
    private int TYPE_BOLD = 1;
    private int TYPE_ITALIC = 2;
    private int FONT_ARIAL = 1;
    private int FONT_OPEN_SANS = 2;
    private int fontType;
    private int fontName;

    public TextViewWithFont(Context context) {
        super(context);
        init(null, 0);
    }
    public TextViewWithFont(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs, 0);
    }
    public TextViewWithFont(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs, defStyle);
    }
    private void init(AttributeSet attrs, int defStyle) {
        // Load attributes
        final TypedArray a = getContext().obtainStyledAttributes(
                attrs, R.styleable.font, defStyle, 0);
        fontName = a.getInt(R.styleable.font_name, defaultDimension);
        fontType = a.getInt(R.styleable.font_type, defaultDimension);
        a.recycle();
        MyApplication application = (MyApplication ) getContext().getApplicationContext();
        if (fontName == FONT_ARIAL) {
            setFontType(application .getArialFont());
        } else if (fontName == FONT_OPEN_SANS) {
            setFontType(application .getOpenSans());
        }
    }
    private void setFontType(Typeface font) {
        if (fontType == TYPE_BOLD) {
            setTypeface(font, Typeface.BOLD);
        } else if (fontType == TYPE_ITALIC) {
            setTypeface(font, Typeface.ITALIC);
        } else {
            setTypeface(font);
        }
    }
}

and in xml

<com.example.customwidgets.TextViewWithFont
        font:name="Arial"
        font:type="bold"
        android:layout_width="wrap_content"
        android:text="Hello world "
        android:padding="5dp"
        android:layout_height="wrap_content"/>

dont forget to add the schema in root of your xml

xmlns:font="http://schemas.android.com/apk/res-auto"

And create an attrs.xml file inside values directory, which is holding our custom attribues:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="font">
        <attr name="type">
        <enum name="bold" value="1"/>
            <enum name="italic" value="2"/>
        </attr>
        <attr name="name">
            <enum name="Arial" value="1"/>
            <enum name="OpenSans" value="2"/>
        </attr>
    </declare-styleable>
</resources>

Update:

Found some performance issue when this custom view is used in listview, that is because the font Object is creating every time the view is loaded. Solution I found is to initialize the font in Application Class and refer that font object by

MyApplication application = (MyApplication) getContext().getApplicationContext();

Application class will look like this

public class MyApplication extends Application {

    private Typeface arialFont, openSans;

    public void onCreate() {
        super.onCreate();

        arialFont = Typeface.createFromAsset(getAssets(), QRUtils.FONT_ARIAL);
        openSans = Typeface.createFromAsset(getAssets(), QRUtils.FONT_OPEN_SANS);
    }

    public Typeface getArialFont() {
        return arialFont;
    }

    public Typeface getOpenSans() {
        return openSans;
    }
}
查看更多
登录 后发表回答