Android字体方案 TypeFace
android默认的字体
Android系统默认支持三种字体,分别为:“sans”, “serif”, “monospace"。
替换方案1
可以通过ID查找到View,然后挨个为它们设置字体。
Typeface customFont = Typeface.createFromAsset(this.getAssets(), "fonts/YourCustomFont.ttf");
TextView view = (TextView) findViewById(R.id.activity_main_header);
view.setTypeface(customFont);
这种方案在大量替换下非常麻烦。
替换方案2
你可以为每个文本组件创建一个子类,如TextView、Button等,然后在构造函数中加载自定义字体。
public class BrandTextView extends TextView {
public BrandTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public BrandTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public BrandTextView(Context context) {
super(context);
}
@Override
public void setTypeface(Typeface tf, int style) {
if (style == Typeface.BOLD) {
super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/YourCustomFont_Bold.ttf"));
} else {
super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/YourCustomFont.ttf"));
}
}
}
github方案
/**
* Helper class to apply custom font from assets to all text views in the specified root
* view.
*
* @author Alexander Naberezhnov
*/
public class FontHelper {
/**
* Apply specified font for all text views (including nested ones) in the specified
* root view.
*
* @param context
* Context to fetch font asset.
* @param root
* Root view that should have specified font for all it's nested text
* views.
* @param fontPath
* Font path related to the assets folder (e.g. "fonts/YourFontName.ttf").
*/
public static void applyFont(final Context context, final View root, final String fontPath) {
try {
if (root instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) root;
int childCount = viewGroup.getChildCount();
for (int i = 0; i < childCount; i++)
applyFont(context, viewGroup.getChildAt(i), fontPath);
} else if (root instanceof TextView)
((TextView) root).setTypeface(Typeface.createFromAsset(context.getAssets(), fontPath));
} catch (Exception e) {
Log.e(TAG, String.format("Error occured when trying to apply %s font for %s view", fontPath, root));
e.printStackTrace();
}
}
}