Skip to content Skip to sidebar Skip to footer

Font In Android Library

At the follow link Android Dev Guide is write: Library projects cannot include raw assets The tools do not support the use of raw asset files (saved in the assets/ directory) in a

Solution 1:

Here's a method for loading fonts from resources that actually works ;-) Credit to mr32bit for the first version.

private Typeface getFontFromRes(int resource)
{ 
    Typeface tf = null;
    InputStream is = null;
    try {
        is = getResources().openRawResource(resource);
    }
    catch(NotFoundException e) {
        Log.e(TAG, "Could not find font in resources!");
    }

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

    try
    {
        byte[] buffer = newbyte[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();

        tf = Typeface.createFromFile(outPath);

        // clean upnew File(outPath).delete();
    }
    catch (IOException e)
    {
        Log.e(TAG, "Error reading in font!");
        returnnull;
    }

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

    return tf;      
}

Solution 2:

Ok I have found a workaround for the problem. You need to copy the file to an external directory then load a typeface from file with Typeface.createFromFile and then delete the temporary file. I know is not a clean mode of work but is working grate.

1 - You need to put your font on "/res/raw/font.ttf"

2 - Inser in your code the following method

3 - put in your code Typeface mFont = FileStreamTypeface(R.raw.font);

4 - All is done

 Typeface FileStreamTypeface(int resource)
{
    Typefacetf=null;

    InputStreamis= getResources().openRawResource(resource);
    Stringpath= Environment.getExternalStorageDirectory().getAbsolutePath() + "/gmg_underground_tmp";
    Filef=newFile(path);
    if (!f.exists())
    {
        if (!f.mkdirs())
            returnnull;
    }

    StringoutPath= path + "/tmp.raw";

    try
    {
        byte[] buffer = newbyte[is.available()];
        BufferedOutputStreambos=newBufferedOutputStream(newFileOutputStream(outPath));

        intl=0;
        while((l = is.read(buffer)) > 0)
        {
            bos.write(buffer, 0, l);
        }
        bos.close();

        tf = Typeface.createFromFile(outPath);

        Filef2=newFile(outPath);
        f2.delete();
    }
    catch (IOException e)
    {
        returnnull;
    }

    return tf;      
}

if someone have an alternative I'm pleased to read it. Do you have to remember that this workaround is only for Android Libraries

Best regards

Solution 3:

Intellij Idea (and android studio as it's based on intellij) has a feature that let you include the asset files of the library module to application module, I don't know about other environment.

Go to project structure in file menu, then facets, choose application module, in compiler tab check "include assets from dependencies to the into APK" checkbox.

As intellij is far better than Eclipse, I think migrating is reasonable.

EDIT:

Asset and manifest merging are fully supported in android studio.

Solution 4:

If you extend a TextView and want to use many of this views you should have only one instance of the Typeface in this view. Copy the *.ttf file into res/raw/ and use the following code:

publicclassMyTextViewextendsTextView {
    publicstaticfinalStringFONT="font.ttf";
    privatestatic Typeface mFont;

    privatestatic Typeface getTypefaceFromFile(Context context) {
        if(mFont == null) {
            Filefont=newFile(context.getFilesDir(), FONT);
            if (!font.exists()) {
                copyFontToInternalStorage(context, font);
            }
            mFont = Typeface.createFromFile(font);
        }
        return mFont;
    }

    privatestaticvoidcopyFontToInternalStorage(Context context, File font) {
        try {
            InputStreamis= context.getResources().openRawResource(R.raw.font);
            byte[] buffer = newbyte[4096];
            BufferedOutputStreambos=newBufferedOutputStream(newFileOutputStream(font));
            int readByte;
            while ((readByte = is.read(buffer)) > 0) {
                bos.write(buffer, 0, readByte);
            }
            bos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    publicMyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setTypeface(getTypefaceFromFile(context));
    }
}

mFont is a static variable, so the reference will not be destroyed and can be reused in other MyTextViews. This code is nearly the same as the other answers but I guess mor efficient and consumes less memory if you are using it in a ListView or something.

Solution 5:

So if I want to create a custom view component that use a custom font how can I access the resource?

Your code would access it the same way that it does not. You will simply have to tell reusers of your custom view to include the font file in their assets.

Can't I redistribute my component with my favorite font !!!!

Sure you can. Put the font in a ZIP file along with the rest of your library project, along with instructions for where to place it in a project. Be sure to use a font that you have rights to redistribute this way, though.

Post a Comment for "Font In Android Library"