How can i use the custom font which we add in asset folder in xml? I want to create custom font for app.. but I run the programme ,it has exception. this is my java code:
public class MainActivity extends TextView {
private static final String TAG = "TextView";
public MainActivity(Context context) {
super(context);
}
public MainActivity(Context context, AttributeSet attrs) {
super(context, attrs);
setCustomFont(context, attrs);
}
public MainActivity(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setCustomFont(context, attrs);
}
private void setCustomFont(Context ctx, AttributeSet attrs) {
TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.textfont);
String customFont = a.getString(R.styleable.TextViewPlus_customFont);
setCustomFont(ctx, customFont);
a.recycle();
}
public boolean setCustomFont(Context ctx, String asset) {
Typeface tf = null;
try {
tf = Typeface.createFromAsset(ctx.getAssets(), asset);
} catch (Exception e) {
Log.e(TAG, "Could not get typeface: "+e.getMessage());
return false;
}
setTypeface(tf);
return true;
}
}
and create a folder in res/values/attrs
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="textfont">
<attr name="customFont" format="string"/>
</declare-styleable>
</resources>
and xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:foo="http://schemas.android.com/apk/res/com.example.changfont"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.example.changfont.MainActivity
android:id="@+id/textViewPlus1"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:text="helooo"
foo:customFont="aaa.ttf">
</com.example.changfont.MainActivity>
logcat is:
09-09 20:44:28.063: E/AndroidRuntime(11515): FATAL EXCEPTION: main
09-09 20:44:28.063: E/AndroidRuntime(11515): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.changfont/com.example.changfont.MainActivity}: java.lang.InstantiationException: can't instantiate class com.example.changfont.MainActivity; no empty constructor
09-09 20:44:28.063: E/AndroidRuntime(11515): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1891)
I do not know what the problem is ? please help me.