Font in Android Library

后端 未结 9 1620
南方客
南方客 2021-02-05 15:30

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 t

9条回答
  •  囚心锁ツ
    2021-02-05 15:57

    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)
    {
        Typeface tf = null;
    
        InputStream is = getResources().openRawResource(resource);
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/gmg_underground_tmp";
        File f = new File(path);
        if (!f.exists())
        {
            if (!f.mkdirs())
                return null;
        }
    
        String outPath = path + "/tmp.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();
    
            tf = Typeface.createFromFile(outPath);
    
            File f2 = new File(outPath);
            f2.delete();
        }
        catch (IOException e)
        {
            return null;
        }
    
        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

提交回复
热议问题