所以我想在android中更改android:fontFamily,但我在android中没有看到任何预定义的字体。如何选择预定义的选项之一?我真的不需要定义我自己的TypeFace,但我所需要的是与现在显示的不同。

<TextView
    android:id="@+id/HeaderText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="52dp"
    android:gravity="center"
    android:text="CallerBlocker"
    android:textSize="40dp"
    android:fontFamily="Arial"
 />

看来我在上面做的事真的行不通!BTW android:fontFamily=“Arial”是一个愚蠢的尝试!


当前回答

我想我已经太迟了,但也许这个解决方案对其他人有帮助。要使用自定义字体,请将字体文件放在字体目录中。

textView.setTypeface(ResourcesCompat.getFont(this, R.font.lato));

其他回答

管理字体的一种简单方法是通过资源声明它们,例如:

<!--++++++++++++++++++++++++++-->
<!--added on API 16 (JB - 4.1)-->
<!--++++++++++++++++++++++++++-->
<!--the default font-->
<string name="fontFamily__roboto_regular">sans-serif</string>
<string name="fontFamily__roboto_light">sans-serif-light</string>
<string name="fontFamily__roboto_condensed">sans-serif-condensed</string>

<!--+++++++++++++++++++++++++++++-->
<!--added on API 17 (JBMR1 - 4.2)-->
<!--+++++++++++++++++++++++++++++-->
<string name="fontFamily__roboto_thin">sans-serif-thin</string>

<!--+++++++++++++++++++++++++++-->
<!--added on Lollipop (LL- 5.0)-->
<!--+++++++++++++++++++++++++++-->
<string name="fontFamily__roboto_medium">sans-serif-medium</string>
<string name="fontFamily__roboto_black">sans-serif-black</string>
<string name="fontFamily__roboto_condensed_light">sans-serif-condensed-light</string>

这是基于这里和这里的源代码

Android不允许您从XML布局设置自定义字体。相反,您必须将特定字体文件绑定到应用程序的assets文件夹中,并以编程方式进行设置。类似于:

TextView textView = (TextView) findViewById(<your TextView ID>);
Typeface typeFace = Typeface.createFromAsset(getAssets(), "<file name>");
textView.setTypeface(typeFace);

注意,只有在调用setContentView()后才能运行此代码。此外,Android只支持某些字体,并且应为.ttf(TrueType)或.otf(OpenType)格式。即使如此,某些字体也可能不起作用。

这是一种在Android上绝对有效的字体,如果Android不支持您的字体文件,您可以使用它来确认您的代码是否有效。

Android O更新:根据Roger的评论,这现在可以在Android O中使用XML。

在res/layout/value/style.xml中设置样式如下:

<style name="boldText">
    <item name="android:textStyle">bold|italic</item>
    <item name="android:textColor">#FFFFFF</item>
</style>

要在main.xml文件中使用此样式,请使用:

style="@style/boldText"

也许我的评论会对某些人有用:我试图了解为什么app:fontFamily=“@font/my_font”不起作用,在浪费了一段时间后发现,有效的解决方案是android:fontFamily=“@font/my_font”

它与android相同:字体。

内置字体有:

典型的桑斯衬线单空间

参见android:字体。