-1

我有这段代码可以从assets文件夹中获取字体文件:

public static Typeface getMyFont(Context context, String resource) {
    InputStream is;
    Typeface font = null;
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    AssetManager assetManager = context.getResources().getAssets();

    try {
        is = classLoader.getResourceAsStream(resource);
        is = assetManager.open(resource);
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while ((line = br.readLine()) != null) {
            Log.e("wwwww", line);
        }
        br.close();
        font = Typeface.createFromAsset(context.getAssets(), line);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return font;
}

这里的资源是链接(快捷方式)的assets文件夹中的font / MYFONT.ttf,但我在这一行得到空指针异常:

font = Typeface.createFromAsset(context.getAssets(), line);
4

2 回答 2

1

我也遇到了同样的问题,您可以尝试使用 try & catch 块围绕添加字体的部分来捕获空指针异常,因此,在我的情况下,

Typeface comingsoon = Typeface.createFromAsset(getApplicationContext().getAssets(), "ComingSoon.ttf");

变成

try{
    Typeface comingsoon = Typeface.createFromAsset(getApplicationContext().getAssets(), "ComingSoon.ttf");
}
catch(NullPointerExecption e){
     //...
}
于 2013-07-20T15:41:29.947 回答
1
    my_font = Typeface.createFromAsset(context.getAssets(), "fonts/MYFONT.ttf"); 
于 2013-03-14T14:07:35.600 回答