源代码:
public class FontUtils {
public static Typeface sTypeface = null;
/**
* 从filePath加载字体
*
* @param context
* @param fileName
* @return Typeface
*/
public static Typeface loadFont(Context context, String fileName) {
sTypeface = Typeface.createFromAsset(context.getAssets(), fileName);
return sTypeface;
}
/**
* 在所有在ViewGroup textview设置字体。递归搜索所有内部ViewGroups。
*/
public static void setFont(ViewGroup group) {
int count = group.getChildCount();
View v;
for (int i = 0; i < count; i++) {
v = group.getChildAt(i);
if (v instanceof TextView || v instanceof EditText || v instanceof Button) {
((TextView) v).setTypeface(sTypeface);
} else if (v instanceof ViewGroup)
setFont((ViewGroup) v);
}
}
/**
* 设置TextView字体
*/
public static void setFont(View v) {
if (v instanceof TextView || v instanceof EditText || v instanceof Button) {
((TextView) v).setTypeface(sTypeface);
}
}
/**
* 从res/raw资源目录中加载字体
*
* @param context Context
* @param resourceId resourceId
* @return Typeface or null
*/
public static Typeface getTypefaceFromRaw(Context context, int resourceId) {
InputStream inputStream = null;
BufferedOutputStream bos = null;
OutputStream os = null;
Typeface typeface = null;
try {
inputStream = context.getResources().openRawResource(resourceId);
String fontFilePath = context.getCacheDir() + "/tmp" + System.currentTimeMillis() + ".raw";
os = new FileOutputStream(fontFilePath);
bos = new BufferedOutputStream(os);
byte[] buffer = new byte[inputStream.available()];
int length = 0;
while ((length = inputStream.read(buffer)) > 0) {
bos.write(buffer, 0, length);
}
typeface = Typeface.createFromFile(fontFilePath);
new File(fontFilePath).delete();
} catch (Resources.NotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
tryClose(bos);
tryClose(os);
tryClose(inputStream);
}
return typeface;
}
/**
* 释放可关闭的对象
*
* @param obj 可关闭的对象
*/
private static void tryClose(Closeable obj) {
if (obj != null) {
try {
obj.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
如果还有补充或者修改的话,请大家留言。