16
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

アプリ独自にフォントファイルを適用するUtilクラス

Posted at
FontMod.java
package com.test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Typeface;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class FontUtil {

	static private Typeface font = null;

	public static void loadFont(String fontFileName, Context context) {
		font = getFontFromZip(fontFileName,context);
	}

	public static void setFont2TextView(View vg) {
		setFont2TextView(vg,font);
	}

	/**
	 * View のフォントを指定する。 ViewGroupの子要素のフォントをすべて一致させる。
	 * 
	 * @param vg
	 * @param font
	 */
	private static void setFont2TextView(View vg, Typeface font) {
		if (font==null)
			return;

		if (vg instanceof ViewGroup) {
			int childCnt = ((ViewGroup) vg).getChildCount();
			if (childCnt > 0) {
				for (int i = 0; i < childCnt; i++) {
					setFont2TextView(((ViewGroup) vg).getChildAt(i), font);
				}
			}
			//ListViewの子要素には適応できない
		} else if (vg instanceof TextView) {
			((TextView) vg).setTypeface(font);
		}
	}

	/**
	 * zip圧縮されているフォントファイルをassetから解凍し、dataフォルダに格納する
	 * assetのファイルはある程度大きいとzip圧縮されていないとAndroidで認識してくれない
	 * @param am
	 * @param fontFileName
	 * @param context
	 * @return
	 */
	private static Typeface getFontFromZip(String fontFileName,Context context) {
		Typeface ret = null;
		File zipFile = null;
		try {
			AssetManager am = context.getAssets();
			InputStream is = am.open(fontFileName,
					AssetManager.ACCESS_STREAMING);

			ZipInputStream zis = new ZipInputStream(is);
			ZipEntry ze = zis.getNextEntry();
			if (ze != null) {
				zipFile = new File(context.getFilesDir(), ze.getName());

				//フォントがすでに解凍されていればなにもしない
				if(zipFile.exists()){
					return Typeface.createFromFile(zipFile.getPath());
				}
				FileOutputStream fos = new FileOutputStream(zipFile, 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();
				ret = Typeface.createFromFile(zipFile.getPath());
			}
			zis.close();
		} catch (Exception e) {
			Log.e("FontUtil", "font extract fail",e);
			if (zipFile!=null && zipFile.exists())
				zipFile.delete();
		}
		return ret;
	}

}
16
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?