Football Fan Football Fan - 10 months ago 44
Java Question

Where to put custom font code for a fragment?

Where to put this:

t = (TextView) findViewById(;
myCustomFont = Typeface.createFromAsset(aiContext.getAssets(),"fonts/bebas.otf");

If i want to show custom font in my Fragment? Please help me guys!


Answer Source

As a bit of expensive use of Typeface.createFromAsset, you can make a singleton class for your custom font & reuse it to your whole app. And you can use any view of your fragment from onCreateView life cycle stage.

Code :

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View  aiView = inflater.inflate(R.layout.fragment_earn_credits, container, false);
    t = (TextView) aiView.findViewById(; // here you should access it by aiVIew
    Typeface typeface = TypefaceManager.getInstance(getActivity()).getTypeFace(TypefaceManager.FONT_TYPE_1);

    return aiView;


Singleton Manager:

public class TypefaceManager {

//write your fonts type here
public final static int FONT_TYPE_1 = 1;

private static TypefaceManager ourInstance ;
private Context context;
private final static SparseArray<Typeface> mTypefaces = new SparseArray<>();

public static TypefaceManager getInstance(Context context) {
    if (ourInstance == null) {
        ourInstance = new TypefaceManager(context.getApplicationContext());
    return ourInstance;

private TypefaceManager(Context context) {
    this.context = context;


public Typeface getTypeFace(int fontType) {

    Typeface typeface = mTypefaces.get(fontType);

    if (typeface == null) {
        typeface = createTypeface(context, fontType);
        mTypefaces.put(fontType, typeface);
    return typeface;

private Typeface createTypeface(Context context, int typefaceValue) throws IllegalArgumentException {
    Typeface typeface;
    switch (typefaceValue) {
        case FONT_TYPE_1:
            typeface = Typeface.createFromAsset(context.getAssets(), "fonts/bebas.otf");

        // write your other font type here

            throw new IllegalArgumentException("Unknown `typeface` attribute value " + typefaceValue);
    return typeface;