默認字體
Android SDK自帶了四種字體:"normal"“monospace",“sans”, “serif”,如下:

字體
看這四兄弟長的還是蠻像,我是看不出多大差別。。。
設置方式
1.通過XML文件設置
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="monospace" android:textSize="20dp" android:textColor="#000000" android:typeface="monospace" android:layout_margin="5dp"/>
2.Java代碼中設置
TextView txtNormal = (TextView) findViewById(R.id.txt_normal);
txtNormal.setTypeface(Typeface.MONOSPACE);
設置第三方字體
Res中使用
右鍵選擇項目的app / res文件夾,然后選擇New > Android resource directory。

image.png
Resource type中選擇font,File name名為font。

image.png
將字體文件拷貝到font中

image.png
java代碼中使用
TextView txtNormal = (TextView) findViewById(R.id.txt_helvetica); Typeface typeface = ResourcesCompat.getFont(this, R.font.helvetica); txtNormal.setTypeface(typeface);
Assets中使用
新建Assets及fonts目錄,並將字體文件拷貝到fonts目錄下

拷貝字體
在java代碼中使用
TextView txtNormal = (TextView) findViewById(R.id.txt_helvetica); Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/helvetica.ttf"); txtNormal.setTypeface(typeface);
第三方框架全局字體設置
這里推薦一個第三方字體設置庫Calligraphy,詳細可以點擊連接
添加依賴
compile 'uk.co.chrisjenx:calligraphy:2.3.0'
新建Application
public class BaseApplication extends Application { @Override public void onCreate() { super.onCreate(); CalligraphyConfig.initDefault(new CalligraphyConfig.Builder() .setDefaultFontPath("fonts/Helvetica.ttf") .setFontAttrId(R.attr.fontPath) .build() ); } }
在Activity中重寫attachBaseContext方法
@Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase)); }
在xml中使用
<TextView android:id="@+id/txt_helvetica" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Lorem ipsum" android:textSize="20dp" android:textColor="#000000" android:layout_margin="5dp" fontPath="fonts/Helvetica.ttf" tools:ignore="MissingPrefix"/>
如果fontPath="fonts/Helvetica.ttf"報錯,在View上添加 tools:ignore="MissingPrefix”即可。
其他具體功能,詳見Calligraphy