TextViewに独自フォントを使用する方法

TextViewで独自フォントを使用するには、フォントファイルをassetsフォルダに設置して指定するか、フォントファイルのパスを指定する方法があります。

AndroidアプリでTextViewに使用できるフォントの一覧
assetsフォルダには1MB以上の非圧縮ファイルを設置できない

assetsフォルダに設置
/assets/fonts/sample.ttfとすると

Typeface typefaceOriginal = Typeface.createFromAsset(getAssets(), "fonts/sample.ttf");

パスを指定

Typeface typefaceOriginal = Typeface.createFromFile(path);

またassetsフォルダには非圧縮ファイルに容量制限があり、フォントファイルがこの容量制限を超える場合は圧縮ファイルにするなどの対応をします。

フォントを圧縮して次の場所に設置
/assets/font/sample.zip

サンプルコード

String path = null;
try {
	AssetManager	am	= getResources().getAssets();
	InputStream	is	= am.open("font/sample.zip", AssetManager.ACCESS_STREAMING);
	ZipInputStream	zis	= new ZipInputStream(is);
	ZipEntry		ze	= zis.getNextEntry();

	if (ze != null) {
		path = getFilesDir().toString() + "/" + ze.getName();
		FileOutputStream fos = new FileOutputStream(path, false);
		byte[] buf = new byte[1024];
		int size = 0;

		while ((size = zis.read(buf, 0, buf.length)) > -1) {
			fos.write(buf, 0, size);
		}
		fos.close();
		zis.closeEntry();
	}
	zis.close();
} catch (Exception e) {
	e.printStackTrace();
}

Typeface typefaceOriginal = null;
if(path != null){
	typefaceOriginal = Typeface.createFromFile(path);
}

関連記事

スポンサーリンク

各メーカーのルーターのID・パスワードの一覧 Y

ホームページ製作・web系アプリ系の製作案件募集中です。

上に戻る