I need to connect the font in the fragment. When did in activit, it worked.

In the fragment the following line:

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

Further for the necessary text in this fragment I connect myfonts with the necessary font.

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

Code class 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); } 

Actually it swears at compilation:

  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 

I tried to change Context to Fragment2 in the Utils class, but it did not work: I did not find the getAssets() method.

  • It is clearly written here that a context is required, and the Fragment class is not its successor (as opposed to activation) - pavlofff

2 answers 2

Try this:

 Typeface myfonts = Utils.getTypeFace(getActivity(), "fonts/a_BentTitulDcFr.ttf"); 
  • it all worked, thanks - Alexey
  • @ Alexey, Great! If the answer helped you to cope with the problem - it should be noted as correct - Werder

I will give an example of how I solved a similar problem:

 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; } } 

In 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); } 

Using the helper class, you can install the fonts you need in the application where they are needed without any problems.