7个解决方案
146 votes
您需要在项目的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上,其名称以小写字母书写)。
Zelimir answered 2019-06-01T01:40:53Z
12 votes
您可以使用自定义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*/);
}
}
}
Jabbir Basha answered 2019-06-01T01:41:18Z
9 votes
在assets文件夹中创建名为fonts的文件夹,并从以下链接添加代码段。
Typeface tf = Typeface.createFromAsset(getApplicationContext().getAssets(),"fonts/fontname.ttf");
textview.setTypeface(tf);
Jana answered 2019-06-01T01:41:42Z
7 votes
要实现您需要使用Typeface通过下面的示例
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);
}
}
}
Jabbir Basha answered 2019-06-01T01:42:06Z
5 votes
完成此任务的最简单方法是打包所需的字体 与您的申请。 为此,只需在中创建资产/文件夹即可 项目根目录,并将您的字体(以TrueType或TTF格式)放入 资产。 例如,您可以创建assets / fonts /并将其设置为 那里有TTF文件。
然后,您需要告诉您的小部件使用该字体。 不幸, 你不能再使用布局XML,因为XML不知道 关于您作为应用程序资产可能隐藏的任何字体。 相反,您需要通过调用来进行Java代码的更改 Typeface.createFromAsset(getAssets(),“fonts / HandmadeTypewriter.ttf”), 然后获取创建的Typeface对象并将其传递给您 TextView通过setTypeface()。
有关这方面的更多参考,我得到了这个教程:
[http://www.androidguys.com/2008/08/18/fun-with-fonts/]
bHaRaTh answered 2019-06-01T01:42:51Z
2 votes
我建议这种方法非常好,在typeface到styles.xml添加自定义字体的名称,并将您的字体集放入assets文件夹。
ar-g answered 2019-06-01T01:43:16Z
2 votes
除了上述答案之外还有一点。在片段内使用字体时,应在onAttach方法(覆盖)中完成字体实例化,如下所示:
@Override
public void onAttach(Activity activity){
super.onAttach(activity);
Typeface tf = Typeface.createFromAsset(getApplicationContext().getAssets(),"fonts/fontname.ttf");
}
原因:
片段附加到活动之前有很短的时间。 如果在将片段附加到活动之前调用CreateFromAsset方法,则会发生错误。
Akil Adeshwar answered 2019-06-01T01:43:53Z