我应用了一个自定义字体TextView,但它似乎没有改变字体。

这是我的代码:

    Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/myFont.ttf");
    TextView myTextView = (TextView)findViewById(R.id.myTextView);
    myTextView.setTypeface(myTypeface);

谁能帮我摆脱这个问题?


当前回答

在尝试了这篇文章中描述的大多数解决方案后,我偶然发现了Calligraphy (https://github.com/chrisjenx/Calligraphy) - Christopher Jenkins的一个库,可以让你轻松地向应用程序添加自定义字体。与这里建议的方法相比,他的库的优点是:

你不必引入自己的重载TextView组件,你使用内置的TextView 您可以使用gradle轻松地包含该库 图书馆不限制你的字体选择;您只需将您喜欢的添加到资产目录 你不仅得到自定义文本视图-所有其他基于文本的Android组件也将显示使用您的自定义字体。

其他回答

在Android O预览版中,最好的方法是: 它只适用于android studio-2.4或更高版本

右键单击res文件夹,进入New > Android资源目录。新 显示“资源目录”窗口。 在“资源类型”列表中选择字体,然后单击“确定”。 在字体文件夹中添加您的字体文件。下面的文件夹结构生成R.font。dancing_script R.font。la_la和R.font.ba_ba。 双击字体文件,在编辑器中预览文件的字体。

接下来,我们必须创建一个字体族:

右键单击字体文件夹,选择新建>字体资源文件。出现“新建资源文件”窗口。 输入文件名,然后单击OK。新的字体资源XML在编辑器中打开。 将每个字体文件、样式和权重属性包含在字体标记元素中。下面的XML演示了如何在字体资源XML中添加与字体相关的属性:

添加字体到TextView:

   <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="@font/hey_fontfamily"/>

从文档来看

使用字体

所有步骤都是正确的。

您可以使用简单的EasyFonts第三方库来设置各种自定义字体到您的TextView。通过使用这个库,你应该不必担心下载和添加字体到assets/fonts文件夹。还有关于字体对象的创建。

而不是

Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/myFont.ttf");
TextView myTextView = (TextView)findViewById(R.id.myTextView);
myTextView.setTypeface(myTypeface);

简单:

TextView myTextView = (TextView)findViewById(R.id.myTextView);
myTextView.setTypeface(EasyFonts.robotoThin(this));

这个库还提供了以下字体面。

Roboto Droid衬线 机器人机器人 自由 有趣的栽培者 Android的国家 绿色的鳄梨 识别

你可以在https://github.com/neopixl/PixlUI上使用PixlUI

导入他们的.jar并在XML中使用它

 <com.neopixl.pixlui.components.textview.TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world"
    pixlui:typeface="GearedSlab.ttf" />

如果你想从网络加载字体或轻松地设置它的样式,你可以使用:

https://github.com/shellum/fontView

例子:

<!--Layout-->
<com.finalhack.fontview.FontView
        android:id="@+id/someFontIcon"
        android:layout_width="80dp"
        android:layout_height="80dp" />

//Java:
fontView.setupFont("http://blah.com/myfont.ttf", true, character, FontView.ImageType.CIRCLE);
fontView.addForegroundColor(Color.RED);
fontView.addBackgroundColor(Color.WHITE);

最简单的解决方案android支持现在!

使用自定义字体在xml:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="@font/[your font resource]"/>

看详细信息:

https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml.html