从我需要开发的应用程序,我收到一个特定的字体,它有很多文件,如FontName-Regular,FontName-Bold,FontName-it。我需要在应用程序的所有textview中使用它。首先我认为这是一件容易的事情。看看SO,发现一个非常好的线程:
here
所以首先我喜欢:
public static void overrideFonts(final Context context, final View v) {
try {
if (v instanceof ViewGroup) {
ViewGroup vg = (ViewGroup) v;
for (int i = 0; i < vg.getChildCount(); i++) {
View child = vg.getChildAt(i);
overrideFonts(context, child);
}
} else if (v instanceof TextView) {
((TextView)v).setTypeface(FONT_REGULAR);
}
} catch (Exception e) {
e.printStackTrace();
// ignore
}
}
在我的活动中onCreate中调用了这个方法。我的应用程序中的每个textView都显示该字体和男孩,我很高兴离开这么容易。直到我到达一些需要粗体字样的窗口(android:textStyle =“bold”)。然后我意识到这个解决方案不能为我提供从资产加载Font-Bold.ttf的可能性。
看起来更进一步,看到一个很好的自定义TextView实现,在同一个SO问题:
public class MyTextView extends TextView {
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyTextView(Context context) {
super(context);
init();
}
public void init() {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "font/chiller.ttf");
setTypeface(tf ,1);
}
}
这看起来更好我的问题是:如果我的控件的Style设置为Bold,我可以如何检测init(),我可以分配请求的TypeFace?
感谢您的时间。
LE。按照以下示例,我已将我的课程更新为:
public class MyTextView extends TextView {
Typeface normalTypeface = Typeface.createFromAsset(getContext().getAssets(), Constants.FONT_REGULAR);
Typeface boldTypeface = Typeface.createFromAsset(getContext().getAssets(), Constants.FONT_BOLD);
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyTextView(Context context) {
super(context);
}
public void setTypeface(Typeface tf, int style) {
if (style == Typeface.BOLD) {
super.setTypeface(boldTypeface/*, -1*/);
} else {
super.setTypeface(normalTypeface/*, -1*/);
}
}
}
那么如果我调试,该应用程序在setTypeFace,它似乎应用粗体,但在我的布局我看不到任何改变,而不是粗体。无论我使用什么字体,我的TextView都没有改变,并且显示默认的android字体。我想知道为什么 ?
我总结了一个博客文章here on my blog可能会帮助某人。