我需要开发一个应用程序,从中收到了一个特定的字体,该字体有许多文件,如FontName-Regular,FontName-Bold,FontName-it。我需要在应用程序的所有文本视图中使用它。一开始我以为这是一项简单的任务。查询 Stack Overflow 发现了一个非常好的线程:这里
所以我首先尝试:
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
}
}
我在我的activity的onCreate方法中调用了这个方法。我的应用程序中的每个textView都显示该字体,我很高兴能够如此轻松地完成。直到我到达一个需要以粗体为Style
(android:textStyle="bold"
)的屏幕时,我意识到这种解决方案无法让我从资产中加载Font-Bold.ttf文件。
然后我进一步查看并在同一SO问题中找到了一个不错的自定义TextView实现:
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);
}
}
这看起来更好了。我的问题是:我如何在 init()
中检测我的控件是否设置为粗体,以便我可以分配请求的字体?
谢谢您的时间。
附:根据下面的示例,我已经更新了我的类:
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字体。我想知道为什么?
我在我的博客文章这里总结了所有内容,也许对某些人有帮助。