从我需要开发的应用程序中,我收到了一种特定字体,其中包含许多文件,例如 FontName-Regular、字体名称-粗体, 字体名称。我需要在应用程序的所有文本视图中使用它。首先我认为这是一项容易的任务。查看SO并发现一个非常好的线程:here https://stackoverflow.com/questions/6926263/add-custom-font-for-complete-android-application
所以首先我确实喜欢:
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 期间调用此方法。我的应用程序中的每个文本视图都显示该字体,天哪,我很高兴能如此轻松地摆脱困境。直到我到达需要一些文本视图的屏幕Bold as Style
(android:textStyle="bold"
)。然后我意识到这个解决方案并没有为我提供加载的可能性粗体字体来自资产的.ttf。
进一步查看,在同一个问题中看到了一个很好的自定义 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()
如果我的控件将 Style 设置为 Bold 或不设置,那么我可以分配请求的 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 字体显示。我想知道为什么 ?
我已经在博客文章中总结了所有内容在我的博客上 http://alinberce.wordpress.com/2012/01/25/using-custom-fonts-in-android-bold-italic-regular-you-name-it/也许它会对某人有所帮助。