【发布时间】:2016-06-17 18:20:39
【问题描述】:
我正在为我的 android 应用程序寻找一些时尚的字体。但问题是如何让我的 android 应用程序支持外部字体。
谢谢。
【问题讨论】:
标签: android android-fonts
我正在为我的 android 应用程序寻找一些时尚的字体。但问题是如何让我的 android 应用程序支持外部字体。
谢谢。
【问题讨论】:
标签: android android-fonts
您需要在项目的 assets 文件夹下创建 fonts 文件夹,并将您的 TTF 放入其中。然后在你的 Activity onCreate()
TextView myTextView=(TextView)findViewById(R.id.textBox);
Typeface typeFace=Typeface.createFromAsset(getAssets(),"fonts/mytruetypefont.ttf");
myTextView.setTypeface(typeFace);
请注意,并非所有 TTF 都能正常工作。在我进行实验时,它只适用于一个子集(在 Windows 上,那些名称是用小写大写字母写的)。
【讨论】:
您可以使用自定义字体为整个应用程序使用自定义 TextView 这是一个示例
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*/);
}
}
}
【讨论】:
在 assets 文件夹中创建一个名为 fonts 的文件夹,并从下面的链接添加 sn-p。
Typeface tf = Typeface.createFromAsset(getApplicationContext().getAssets(),"fonts/fontname.ttf");
textview.setTypeface(tf);
【讨论】:
要实现你需要使用字体通过下面的示例
Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/Roboto/Roboto-Regular.ttf");
for (View view : allViews)
{
if (view instanceof TextView)
{
TextView textView = (TextView) view;
textView.setTypeface(typeface);
}
}
}
【讨论】:
allViews,您必须使用getChildCount() 遍历布局,这样您就可以用简单的for 循环替换foreach。
最简单的方法是打包所需的字体 与您的应用程序。为此,只需在 项目根目录,并将您的字体(以 TrueType 或 TTF 形式)放入 资产。例如,您可以创建 assets/fonts/ 并将您的 TTF 文件在里面。
然后,您需要告诉您的小部件使用该字体。很遗憾, 您不能再为此使用布局 XML,因为 XML 不知道 关于您可能作为应用程序资产隐藏的任何字体。 相反,您需要更改 Java 代码,方法是调用 Typeface.createFromAsset(getAssets(), “字体/HandmadeTypewriter.ttf”), 然后获取创建的字体对象并将其传递给您的 TextView 通过 setTypeface()。
更多参考这里是我得到这个的教程:
【讨论】:
我推荐这个approach,在typeface 中添加自定义字体的名称到styles.xml 并将您的字体集放入assets 文件夹中非常好。
【讨论】:
还有一点除了上述答案。 在片段内使用字体时,字体实例化应在 onAttach 方法(覆盖)中完成,如下所示:
@Override
public void onAttach(Activity activity){
super.onAttach(activity);
Typeface tf = Typeface.createFromAsset(getApplicationContext().getAssets(),"fonts/fontname.ttf");
}
原因:
在片段附加到活动之前有很短的时间。如果在将片段附加到活动之前调用 CreateFromAsset 方法,则会发生错误。
【讨论】: