Android Studio新手:如何导入Roboto及Pacifico等谷歌字体
给Android Studio新手的字体导入指南:Roboto & Pacifico
嘿,刚上手Android Studio的话,导入字体真的没你想的那么难!我来一步步带你搞定Roboto和Pacifico这两个热门字体家族,保证你看完就能操作~
第一步:准备字体文件
首先得把需要的字体文件搞到手:
- Roboto:作为Android的系统默认字体,很多设备自带,但如果要确保所有版本都能一致显示,建议下载完整的家族包(包含常规、粗体、斜体等不同字重样式)。
- Pacifico:这是一款可爱的手写风格字体,下载它的TTF格式文件就行。
第二步:在Android Studio中创建字体资源目录
- 右键点击你的
app模块,选择 New -> Android Resource Directory - 在弹出的窗口里,把
Resource type改成font,然后点击OK。这样你的项目里就会多出一个res/font文件夹,专门用来放字体文件。
第三步:导入字体文件到项目
把下载好的字体文件复制到res/font文件夹里,这里要注意一个关键:文件名必须符合Android的命名规范——只能用小写字母、数字和下划线,不能有空格或大写字母。比如:
Pacifico-Regular.ttf要改成pacifico_regular.ttfRoboto-Bold.ttf改成roboto_bold.ttfRoboto-Regular.ttf改成roboto_regular.ttf
第四步:使用字体(两种方式任选)
方式1:在XML布局中直接使用
最常用的就是在布局文件里给控件指定字体,比如TextView:
<!-- 使用Pacifico字体 --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, Pacifico!" android:fontFamily="@font/pacifico_regular"/> <!-- 使用Roboto粗体字体 --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, Roboto Bold!" android:fontFamily="@font/roboto_bold"/>
如果你导入了Roboto的多个字重,还可以创建一个字体家族XML来统一管理,这样切换字重更方便:
在res/font文件夹下新建一个roboto_family.xml文件,内容如下:
<?xml version="1.0" encoding="utf-8"?> <font-family xmlns:android="http://schemas.android.com/apk/res/android"> <font android:fontStyle="normal" android:fontWeight="400" android:font="@font/roboto_regular"/> <font android:fontStyle="normal" android:fontWeight="700" android:font="@font/roboto_bold"/> <font android:fontStyle="italic" android:fontWeight="400" android:font="@font/roboto_italic"/> </font-family>
之后使用的时候,只需要指定这个家族,再通过textStyle切换样式:
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Roboto Regular" android:fontFamily="@font/roboto_family"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Roboto Bold" android:fontFamily="@font/roboto_family" android:textStyle="bold"/>
方式2:在代码中动态设置
如果需要在运行时动态切换字体,可以用代码实现:
Kotlin版本
// 获取Pacifico字体 val pacificoTypeface = ResourcesCompat.getFont(this, R.font.pacifico_regular) // 给TextView设置字体 myTextView.typeface = pacificoTypeface
Java版本
// 获取Pacifico字体 Typeface pacificoTypeface = ResourcesCompat.getFont(this, R.font.pacifico_regular); // 给TextView设置字体 myTextView.setTypeface(pacificoTypeface);
一些小提示
- 如果你只是想用系统自带的Roboto,也可以直接在XML里写
android:fontFamily="sans-serif"(对应常规体)、sans-serif-bold(粗体),但导入本地文件能避免不同设备上的字体差异。 - 字体文件不要太大,不然会增加APK体积,尽量只导入你需要的字重样式。
内容的提问来源于stack exchange,提问作者HUHO




