Football Fan Football Fan - 20 days ago 6
Java Question

Where to put custom font code for a fragment?

Where to put this:

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


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

EDIT



Fragment.java:

http://pastebin.com/raw/Cs5WC496

Main.java

http://pastebin.com/raw/igirq4p5

Answer

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 :

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

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


    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");
            break;


        // write your other font type here




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

}

Comments