package com.example.tutorial;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;
import java.util.HashMap;
/**
* Created by Shiburagi on 28-Jan-15.
*/
public class CustomTextView extends TextView {
private static final String TAG = "TextView";
private final static HashMap<String, Typeface> fonts;
static {
fonts = new HashMap<String, Typeface>();
}
/**
* Default Constructor
* @param context
*/
public CustomTextView(Context context) {
super(context);
}
/**
* Overload Constructor
* @param context
* @param attrs
*/
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setFont(context, attrs);
}
/**
* Overload Constructor
* @param context
* @param attrs
* @param defStyleAttr
*/
public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setFont(context, attrs);
}
/**
* Overload Constructor
* @param context
* @param attrs
* @param defStyleAttr
* @param defStyleRes
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
setFont(context, attrs);
}
/**
* set font according font attribute been defined in XML layout
* @param context
* @param attrs
*/
private void setFont(Context context, AttributeSet attrs) {
// get All attribute of CustomTextView in xml file
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomTextView);
// get font name from <something>:font attribute
String font = a.getString(R.styleable.CustomTextView_font);
setFont(context, font);
a.recycle();
}
/**
* set font for this TextView.
* @param context
* @param asset
* @return
*/
public boolean setFont(Context context, String asset) {
Typeface typeface = null;
String directory="fonts/";
try {
// if the font not exist yet, then create it and store in HashMap fonts
// otherwise, just call it back.
if(!fonts.containsKey(asset)){
typeface = Typeface.createFromAsset(context.getAssets(),directory.concat(asset));
fonts.put(asset,typeface);
}else{
typeface = fonts.get(asset);
}
} catch (Exception e) {
Log.e(TAG, "Could not get typeface: " + e.getMessage());
return false;
}
// set custom font
setTypeface(typeface);
return true;
}
}