我在我的Android应用程序中使用TextView和EditText的自定义字体。我已经为fonted edittext和textview创建了一个单独的类。我使用Calibri字体作为我的文字。
但在运行我的应用程序后,它在所有文件中显示以下错误 -
com.pack.demo.MyFontedTextView无法实例化MyFontedTextView是类文件的位置,并且com.pack.demo.MyFontedEditText无法实例化。
在我的所有布局中,我将运行时异常作为 -
java.lang.RuntimeException: native typeface cannot be made
at android.graphics.Typeface.<init>(Typeface.java:175)
at android.graphics.Typeface.createFromAsset(Typeface.java:149)
at com.pack.demo.MyFontedTextView.<init>(MyFontedTextView.java:22)
com.pack.demo.MyFontedTextView。(MyFontedTextView.java:22)在Typeface font = Typeface.createFromAsset(context.getAssets(),“calibri.otf”)中显示错误;在下面的类文件中。
以下是我的fonted edittext的代码 -
public class MyFontedEditText extends EditText {
public MyFontedEditText(Context context) {
super(context);
// TODO Auto-generated constructor stub
Typeface font = Typeface.createFromAsset(context.getAssets(),
"calibri.otf");
this.setTypeface(font);
}
public MyFontedEditText(Context context, AttributeSet attrs) {
super(context, attrs);
Typeface font = Typeface.createFromAsset(context.getAssets(),
"calibri.otf");
this.setTypeface(font);
}
public MyFontedEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
Typeface font = Typeface.createFromAsset(context.getAssets(),
"calibri.otf");
this.setTypeface(font);
}
}
同样,我的fonted textview代码 -
public class MyFontedTextView extends TextView {
public MyFontedTextView(Context context) {
super(context);
// TODO Auto-generated constructor stub
Typeface font = Typeface.createFromAsset(context.getAssets(),
"calibri.otf");
this.setTypeface(font);
this.setTypeface(null, Typeface.BOLD);
}
public MyFontedTextView(Context context, AttributeSet attrs) {
super(context, attrs);
Typeface font = Typeface.createFromAsset(context.getAssets(),
"calibri.otf");
Log.d("1", "abc");
this.setTypeface(font);
this.setTypeface(null, Typeface.BOLD);
}
public MyFontedTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
Typeface font = Typeface.createFromAsset(context.getAssets(),
"calibri.otf");
this.setTypeface(font);
this.setTypeface(null, Typeface.BOLD);
}
}
答案 0 :(得分:1)
请尝试这种方式,希望这有助于您解决问题。
public class MyFontedTextView extends TextView {
private Context context;
public MyFontedTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
public MyFontedTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public MyFontedTextView(Context context) {
super(context);
this.context=context;
init(context);
}
private void init(Context mContext) {
try {
Typeface tf = Typeface.createFromAsset(mContext.getAssets(), "calibri.otf");
setTypeface(tf,Typeface.BOLD);
} catch (Throwable e) {
}
}
}