Skip to content

Instantly share code, notes, and snippets.

@KazaKago
Last active September 11, 2015 02:35
Show Gist options
  • Save KazaKago/e504394f41737ee31adb to your computer and use it in GitHub Desktop.
Save KazaKago/e504394f41737ee31adb to your computer and use it in GitHub Desktop.
フォント設定可能なTextViewクラス
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="FontableTextView">
<attr name="font" format="string"/>
</declare-styleable>
</resources>
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
import apps.ignisamerica.flashlight.R;
/**
* フォント設定可能なTextViewクラス
*/
public class FontableTextView extends TextView {
private String mFont;
public FontableTextView(Context context) {
super(context);
}
public FontableTextView(Context context, AttributeSet attrs) {
super(context, attrs);
mFont = readFontFromXml(context, attrs);
reflectFont(mFont);
}
public FontableTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mFont = readFontFromXml(context, attrs);
reflectFont(mFont);
}
public FontableTextView(Context context, String font) {
super(context);
mFont = font;
reflectFont(mFont);
}
public FontableTextView(Context context, AttributeSet attrs, String font) {
super(context, attrs);
mFont = font;
reflectFont(mFont);
}
public FontableTextView(Context context, AttributeSet attrs, int defStyle, String font) {
super(context, attrs, defStyle);
mFont = font;
reflectFont(mFont);
}
/**
* フォントファイルを読み込む
*
* @param context
* @param attrs
*/
private String readFontFromXml(Context context, AttributeSet attrs) {
String font = null;
try {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FontableTextView);
font = a.getString(R.styleable.FontableTextView_font);
a.recycle();
}catch (Exception e){
e.printStackTrace();
}
return font;
}
/**
* フォントを反映
*/
private void reflectFont(String font) {
try {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(), font);
setTypeface(tf);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* フォントを取得
*
* @return
*/
public String getFont() {
return mFont;
}
/**
* フォントを設定
*
* @return
*/
public void setFont(String font) {
mFont = font;
reflectFont(font);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment