我正在为我的 android 应用程序寻找一些时尚的字体。但问题是如何让我的 android 应用程序支持外部字体。
谢谢你。
您需要在项目的 assets 文件夹下创建 fonts 文件夹并将您的 TTF 放入其中。然后在你的活动 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 的文件夹,并从以下链接添加代码段。
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);
}
}
}
完成此操作的最简单方法是将所需字体与您的应用程序打包在一起。为此,只需在项目根目录中创建一个 assets/ 文件夹,然后将您的字体(以 TrueType 或 TTF 形式)放入资产中。例如,您可以创建 assets/fonts/ 并将您的 TTF 文件放在那里。
然后,您需要告诉您的小部件使用该字体。不幸的是,您不能再为此使用布局 XML,因为 XML 不知道您可能作为应用程序资产隐藏的任何字体。相反,您需要在 Java 代码中进行更改,方法是调用 Typeface.createFromAsset(getAssets(), “fonts/HandmadeTypewriter.ttf”),然后获取创建的 Typeface 对象并通过 setTypeface() 将其传递给 TextView。
更多参考这里是我得到这个的教程:
我推荐这种方法,添加自定义字体的名称typeface
并将styles.xml
您的字体集放入assets
文件夹中非常好。
除了上述答案之外,还有一点。在片段内使用字体时,字体实例化应在 onAttach 方法(覆盖)中完成,如下所示:
@Override
public void onAttach(Activity activity){
super.onAttach(activity);
Typeface tf = Typeface.createFromAsset(getApplicationContext().getAssets(),"fonts/fontname.ttf");
}
原因:
在片段附加到活动之前有很短的时间。如果在将片段附加到活动之前调用 CreateFromAsset 方法,则会发生错误。