简体   繁体   English

如何在android库上使用自定义字体

[英]how to use custom fonts on android Library

Basically, I am trying to import ttf fonts into the library project. 基本上,我试图将ttf字体导入到库项目中。 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. 由于您无法在Assets / fonts文件夹中导入ttf,因此我试图将其导入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. 一直在寻找解决方案,但是似乎没有什么具体的方法,因为大多数人只会导入非图书馆项目并使用Typeface.createFromAsset。

I having some difficulties loading them into the xml with a custom view: 我在使用自定义视图将它们加载到xml时遇到一些困难:

 <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: 试图在TextFontView子类中实现以下代码,但是在尝试在先前的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;      
    }

You should be able to put your font.ttf file into assert , and that's where you should put it. 您应该可以将font.ttf文件放入assert ,这是应该放置它的地方。

This link should help. 该链接应该有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM