Font in Android Library

后端 未结 9 1630
南方客
南方客 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:54

    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:

    public class MyTextView extends TextView {
        public static final String FONT = "font.ttf";
        private static Typeface mFont;
    
        private static Typeface getTypefaceFromFile(Context context) {
            if(mFont == null) {
                File font = new File(context.getFilesDir(), FONT);
                if (!font.exists()) {
                    copyFontToInternalStorage(context, font);
                }
                mFont = Typeface.createFromFile(font);
            }
            return mFont;
        }
    
        private static void copyFontToInternalStorage(Context context, File font) {
            try {
                InputStream is = context.getResources().openRawResource(R.raw.font);
                byte[] buffer = new byte[4096];
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(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();
            }
        }
    
        public MyTextView(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.

提交回复
热议问题