how to use custom fonts on android Library

1.4k views Asked by At

Basically, I am trying to import ttf fonts into the library project. But I am having some problems. Since you can't import ttf in the assets/fonts folder, I was trying to import them in res/raw. Been searching for a solution but there doesn't seem to be anything concrete since most people would just import into a non library project and using Typeface.createFromAsset.

I having some difficulties loading them into the xml with a custom view:

 <com.demo.helpers.TextFontView
                    android:id="@+id/login_title_lbl"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/mob_LogIn"
                    android:textColor="@color/white"
                    android:textSize="@dimen/font_login"
                    demo:fontFace="+id/opensans-regular"
                     />

Was trying to implement the following code in the TextFontView subclass, but i am having some difficulties trying to link it in the previous xml:

public static Typeface getgetTypefaceFromRes(Context context, int resource)
    { 
        Typeface typeFace = null;
        InputStream is = null;
        try {
            is = context.getResources().openRawResource(resource);
        }
        catch(NotFoundException e) {
            Log.e("Typeface", "Could not find font in resources!");
        }

        String outPath = context.getCacheDir() + "/tmp" + System.currentTimeMillis() + ".raw";

        try
        {
            byte[] buffer = new byte[is.available()];
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outPath));

            int l = 0;
            while((l = is.read(buffer)) > 0)
                bos.write(buffer, 0, l);

            bos.close();

            typeFace = Typeface.createFromFile(outPath);

            // clean up
            new File(outPath).delete();
        }
        catch (IOException e)
        {
            Log.e("Typeface", "Error reading in font!");
            return null;
        }

        Log.d("Typeface", "Successfully loaded font.");

        return typeFace;      
    }
1

There are 1 answers

1
Chris On

You should be able to put your font.ttf file into assert, and that's where you should put it.

This link should help.