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
The code below modifies the solution from @bk138 and includes @Jason Robinson recommendations for not deleting the file and checking for a previously cached file first. Also, it names the temp file after the font instead of the time created.
public static Typeface getFontFromRes(Context context, int resId, boolean deleteAfterwards){
String tag = "StorageUtils.getFontFromRes";
String resEntryName = context.getResources().getResourceEntryName(resId);
String outPath = context.getCacheDir() + "/tmp_" + resEntryName + ".raw";
//First see if the file already exists in the cachDir
FileInputStream fis = null;
try {
fis = new FileInputStream(new File(outPath));
} catch (FileNotFoundException e) {
Log.d(tag,"fileNotFoundException outPath:"+outPath+e.getMessage());
}
if(fis != null){
try {
Log.d(tag,"found cached fontName:"+resEntryName);
fis.close();
} catch (IOException e) {
Log.d(tag,"IOException outPath:"+outPath+e.getMessage());
}
//File is already cached so return it now
return Typeface.createFromFile(outPath);
}
InputStream is = null;
try {
is = context.getResources().openRawResource(resId);
}catch(NotFoundException e) {
Log.e(tag, "Could not find font in resources! " + outPath);
}
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();
}catch (IOException e){
Log.e(tag, "Error reading in font!");
return null;
}
Typeface tf = Typeface.createFromFile(outPath);
if(deleteAfterwards){
// clean up if desired
new File(outPath).delete();
}
Log.d(tag, "Successfully loaded font.");
return tf;
}