1

Мне нужно подключить шрифт в фрагменте. Когда делал в активити, то работало.

В фрагменте такая строчка:

Typeface myfonts = Utils.getTypeFace(this, "fonts/a_BentTitulDcFr.ttf");

Далее для нужного текста в этом фрагменте я подключаю myfonts с нужным шрифтом.

mSelectedItemView2 = (TextView) v.findViewById(R.id.selected_item2);
mSelectedItemView2.setTypeface(myfonts);

Код класс Utils.java

public class Utils {

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

public static Typeface getTypeFace(Context context, String assetPath) {
    synchronized (cache) {
        if (!cache.containsKey(assetPath)) {
            try {
                Typeface typeFace = Typeface.createFromAsset(context.getAssets(), assetPath);
                cache.put(assetPath, typeFace);
            } catch (Exception e) {
                Log.e("TypeFaces", "Typeface not loaded.");
                return null;
            }
        }
        return cache.get(assetPath);
    }

Собственно он ругается при компиляции:

    Error:(40, 33) error: method getTypeFace in class Utils cannot be applied to given types;
required: Context,String
found: Fragment2,String
reason: actual argument Fragment2 cannot be converted to Context by method invocation conversion

пытался поменять Context на Fragment2 в классе Utils, но не заработало: не нашел метод getAssets().

1
  • Здесь ясно написано, что требуется контекст, а класс Fragment не является его наследником (в отличии от активити)
    – pavlofff
    27 июл 2016 в 16:44

2 ответа 2

2

Приведу пример того, как я решил подобную проблему:

import android.graphics.Typeface;

public class FontsHelper {

    private static FontsHelper instance;
    private static Typeface roboto_regular;
    private static Typeface roboto_medium;


    private FontsHelper() {
    }

    public synchronized static FontsHelper instance() {
        if (instance == null) {
            instance = new FontsHelper();
        }
        return instance;
    }

    public void setFontRobotoRegular(Typeface typeface) {
        FontsHelper.roboto_regular = typeface;
    }

    public void setFontRobotoMedium(Typeface typeface) {
        FontsHelper.roboto_medium = typeface;
    }

    public static Typeface getFontRobotoRegular() {
        return roboto_regular;
    }

    public static Typeface getFontRobotoMedium() {
        return roboto_medium;
    }

}

В Main Activity:

private void setRobotoFont() {    
robotoRegularFont = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Regular.ttf");
 robotoMediumFont = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Medium.ttf");
                setFontsHelper();
            }



private void setFontsHelper() {
    FontsHelper.instance().setFontRobotoRegular(robotoRegularFont);
    FontsHelper.instance().setFontRobotoMedium(robotoMediumFont);
}

Используя класс-хелпер вы можете устанавливать нужные вам шрифты в приложении где они потребуются безо всяких проблем.

0
0

Попробуйте так:

Typeface myfonts = Utils.getTypeFace(getActivity(), "fonts/a_BentTitulDcFr.ttf");
2
  • все заработало, спасибо 27 июл 2016 в 18:53
  • @Алексей, Отлично! Если ответ помог вам справиться с проблемой - следует отметить его как верный
    – Werder
    28 июл 2016 в 6:17

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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