4

Как добавить в приложение свой шрифт и присвоить элементу TextView?

1

2 ответа 2

16

Краткий вариант

TextView textView = (TextView) findViewById(<your TextView ID>);
Typeface typeFace = Typeface.createFromAsset(getAssets(), "<file name>");
textView.setTypeface(typeFace);

Но лучше (ну, просто кто-то любит более полные решения и не любит копировать одно и то же для всех 128 TexView в приложении) отнаследоваться от TextView:

com/example/foo/view/FontableTextView.java

public class FontableTextView extends TextView {
    public FontableTextView(Context context) {
        super(context);
    }

    public FontableTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        UiUtil.setCustomFont(this, context, attrs,
                R.styleable.com_example_foo_view_FontableTextView,
                R.styleable.com_example_foo_view_FontableTextView_font);
    }

    public FontableTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        UiUtil.setCustomFont(this, context, attrs,
                R.styleable.com_example_foo_view_FontableTextView,
                R.styleable.com_example_foo_view_FontableTextView_font);
    }
}

res/values/attr.xml

<resources>
    ...
    <attr name="font" format="string" />
    <declare-styleable name="com.example.foo.view.FontableTextView">
        <attr name="font" />
    </declare-styleable>
</resources>

res/layuot/main_activity.xml

...
<com.example.foo.FontableTextView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     app:font="coolfont.ttf" />
...

com/example/foo/utils/UiUtil.java

public class UiUtil {

    public static final String TAG = "UiUtil";

    public static void setCustomFont(View textViewOrButton, Context ctx, AttributeSet attrs, int[] attributeSet, int fontId) {
        TypedArray a = ctx.obtainStyledAttributes(attrs, attributeSet);
        String customFont = a.getString(fontId);
        setCustomFont(textViewOrButton, ctx, customFont);
        a.recycle();
    }

    private static boolean setCustomFont(View textView, Context ctx, String asset) {
        if (TextUtils.isEmpty(asset))
            return false;
        Typeface tf = null;
        try {
            tf = getFont(ctx, asset);
            if (textView instanceof TextView) {
                ((TextView) textView).setTypeface(tf);
            }
        } catch (Exception e) {
            Log.e(TAG, "Could not get typeface: " + asset, e);
            return false;
        }

        return true;
    }

    private static final Hashtable<String, SoftReference<Typeface>> fontCache = new Hashtable<String, SoftReference<Typeface>>();

    public static Typeface getFont(Context c, String name) {
        synchronized (fontCache) {
            if (fontCache.get(name) != null) {
                SoftReference<Typeface> ref = fontCache.get(name);
                if (ref.get() != null) {
                    return ref.get();
                }
            }

            Typeface typeface = Typeface.createFromAsset(
                    c.getAssets(),
                    "fonts/" + name
            );
            fontCache.put(name, new SoftReference<Typeface>(typeface));

            return typeface;
        }
    }

}

Сам шрифт положить в assets/fonts, в частности:

 assets/fonts/coolfont.ttf
1
  • if (textView instanceof TextView) { намекает на то, что данный подход можно расширить и для других виджетов... 7 июн 2015 в 23:31
0
Typeface.createFromAsset
textView.setTypeface(typeFace)
2
  • TextView программа, этим приложением легко создать любой текст 3 апр 2019 в 1:47
  • Разумеется, первым делом вы должны скачать шрифт или шрифты на свой компьютер. В сети вы можете найти огромное количество совершенно бесплатных шрифтов 3 апр 2019 в 2:01

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.