我试图在Android Studio中使用自定义字体,就像我们在Eclipse中所做的那样。但不幸的是,不知道在哪里放“资产”文件夹!


当前回答

芬兰湾的科特林回答

如果你需要在代码方面使用字体,你可以使用这个功能,它也有版本代码控制。

fun getFontJarvisWhite(): Typeface {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) resources.getFont(R.font.jarvis_white)
    else context?.let { ResourcesCompat.getFont(it, R.font.jarvis_white) }!!
}

其他回答

我无法加载字体,因为我将字体文件命名为Poppins-Medium。Tff,重命名为poppins_medium。TFF对我很管用。 其余步骤保持不变:

在res文件夹下创建字体资源目录 将tff文件复制并粘贴到该目录中 然后在XML的TextView中使用fontFamily属性。 如果以上步骤不起作用,您可以使用此链接创建该字体的FontFamily

现在有很多应用字体的方法,最简单的方法之一是这样的, 1)右键单击res文件夹 进入“新建> Android资源目录”。

2)从资源类型列表中选择字体,然后单击确定。

3)把你的字体文件放在字体文件夹里。

如果你像我一样对Android非常陌生,这可能有点棘手。请务必致电:

TextView myTextView = (TextView) findViewById(R.id.textView);
Typeface typeface=Typeface.createFromAsset(getAssets(), "fonts/your font.ttf");
myTextView.setTypeface(typeface);

方法,例如onCreate。

2021年更新:

在res文件夹中创建一个名为font的文件夹并复制您的字体

所有字体名称只能为:小写字母a-z、0-9或下划线。

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

编程使用:

textView.setTypeface(ResourcesCompat.getFont(context, R.font.abc_font))

对于Android Studio 4.2+,现在甚至有一个菜单选项:

首先在字体文件夹中添加font.ttf文件。然后在onCreate方法中添加这一行

    Typeface typeface = ResourcesCompat.getFont(getApplicationContext(), R.font.myfont);
    mytextView.setTypeface(typeface);

这是我的xml

            <TextView
            android:id="@+id/idtext1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="7dp"
            android:gravity="center"
            android:text="My Text"
            android:textColor="#000"
            android:textSize="10sp"
        />