字体导致"不幸(应用程序名称)已停止"

时间:2015-04-02 19:57:18

标签: java android typeface android-fonts

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)

1 个答案:

答案 0 :(得分:-1)

通常你应该这样做:

Typeface typeface = Typeface.createFromAsset(getContext().getAssets(), name+".tff");