在BaseGameActivity.java
我有方法可以轻松创建字体。但不幸的是,当创建字体时,应用程序停止了。该代码不包含语法错误。
BaseGameActivity.java
public class BaseGameActivity extends Activity {
private Map<String,Typeface> typefaces = new HashMap<String,Typeface>();
protected void addTypeface(String name) {
Typeface typeface = Typeface.createFromAsset(getAssets(), name+".tff");
typefaces.put(name, typeface);
}
protected void setTypeface(TextView v, String typefaceName) {
Typeface t = typefaces.get(typefaceName);
if(t != null) {
v.setTypeface(t);
}
}
}
MainAcitivity.java
public class MainActivity extends BaseGameActivity {
private static final String FONTNAME = "airmole";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addTypeface(FONTNAME);
setTypeface((TextView) findViewById(R.id.title), FONTNAME);
}
}
文件airmole.tff
位于assets
文件夹中。
logcat的
Caused by: java.lang.RuntimeException: native typeface cannot be made
at android.graphics.Typeface.<init>(Typeface.java:319)
at android.graphics.Typeface.createFromAsset(Typeface.java:293)
at de.ucarweb.tools.BaseGameActivity.addTypeface(BaseGameActivity.java:23)
at de.ucarweb.silverball.MainActivity.onCreate(MainActivity.java:28)
at android.app.Activity.performCreate(Activity.java:5372)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
at android.app.ActivityThread.access$700(ActivityThread.java:159)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
答案 0 :(得分:-1)
通常你应该这样做:
Typeface typeface = Typeface.createFromAsset(getContext().getAssets(), name+".tff");