免費論壇 繁體 | 簡體
Sclub交友聊天~加入聊天室當版主
分享
返回列表 回復 發帖

Android 設定 TextView 的字型

原文

Android 在設定文字的字型,
除了調用內建的字型外, 也可以引用外部的字型




TextView mTextView = (TextView) findViewById(R.id.mTextView);
mTextView.setTypeface(
Typeface.createFormAsset(getAssets(), "fonts/HandmadeTypewriter.ttf")
);


必需將引用的字型檔, 放置於 fonts 的目錄底下,
透過 AssetsManage 來引用外部的資源, 即可設定該字型,
但需注意該字型必需為 TTF (True Type Font) 的格式,
否則會造成字型無法顯示、或是程式無法編譯的問題

除了以 createFromAsset 的方式來調用外部的字型外
也可以利用 defaultFromStyle 的方式來使用 Android 內建的字型

除將字型直接放入手機中, 也可以以 import 的方式來匯入專案





Resources.StyledAttributes resFont =
   getContext().obtainStyledAttributes
   (attrs, R.styleable.UnicodeTextView);
String fontName = resFont.getString(R.styleable.UnicodeTextView_font);

if(fontName != null) {
   // 在這理處理變更字型的程式
}
-----------------------------------------------------------------------------------


原文



Android 內建有 Sans、Serif 及 Monospace 等三種字型,只要在 layout 設定時指定就可以了:

[url=]檢視原始碼[/url] XML
1android:typeface="font name"

那有辦法使用自訂的字型嗎?筆者是不曉得其它的平台是否可行,但在 Android 上是一件很簡單不過的事。首先在專案中的 assets 資料夾中建立一個名為 fonts 的資料夾,接著在把字型檔放入該資料夾:


接著只要利用 Typeface 就能把自訂的字型給其它元件使用囉。

[url=]檢視原始碼[/url] Android
1234567import android.graphics.Typeface;import android.widget.TextView; Typeface font = Typeface.createFromAsset(getAssets(), "fonts/Bleeding Cowboys.ttf"); TextView custom = (TextView)findViewById(R.id.customFont);custom.setTypeface(font);

接著...接著就直接看效果了:

createFromAsset 是從 assets 資料夾中來取得程式包中的內容,若是要從其它位置來取得字型檔的話,則可以使用 createFromFile

[url=]檢視原始碼[/url] Android
12345678import android.graphics.Typeface;import android.widget.TextView; // Bleeding Cowboys.ttf 放在 sdcard 的根目錄下Typeface font = Typeface.createFromFile("sdcard/Bleeding Cowboys.ttf"); TextView custom = (TextView)findViewById(R.id.customFont);custom.setTypeface(font);

這樣就算開發者沒有提供字型檔案,只要有提供讀取字型的功能就可以囉!另外要注意的是,字型檔案只要放在 assets 資料夾中就可以了,多一層 fonts 資料夾做好分類而已。但檔名的大小寫是要一致的才行。
返回列表