我试图从" assets \ font"加载自定义字体文件夹
这是我的" TypefaceSingelton "班级代码:
public class TypefaceSingelton {
private static TypefaceSingelton instance = new TypefaceSingelton();
private TypefaceSingelton() {}
public static TypefaceSingelton getInstance() {
return instance;
}
public static Typeface getFont() {
return Typeface.createFromAsset(AppContext.getAppContext().
getResources().getAssets(), "fonts/Myfont.otf");
}
}
和我的" AppContext " class:
public class AppContext extends Application {
public static Context context;
@Override
public void onCreate(){
super.onCreate();
AppContext.context = getApplicationContext();
}
public static Context getAppContext() {
return AppContext.context;
}
}
以及我如何在MainActivity中使用它:
public class MainActivity extends Activity {
private final Typeface FontTF = TypefaceSingelton.getFont();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final AutoCompleteTextView CtextView = (AutoCompleteTextView) findViewById(R.id.autoComplete);
CtextView.setTypeface(FontTF);
它在" Typeface.createFromAsset"中给出了异常。在TypefaceSingelton里面:
08-16 07:55:51.834: E/AndroidRuntime(3109): Caused by: java.lang.NullPointerException
08-16 07:55:51.834: E/AndroidRuntime(3109): at com.test.TypefaceSingelton.getFont(TypefaceSingelton.java:20)
08-16 07:55:51.834: E/AndroidRuntime(3109): at com.test.MainActivity.onCreate(MainActivity.java:133)
08-16 07:55:51.834: E/AndroidRuntime(3109): at android.app.Activity.performCreate(Activity.java:5104)
08-16 07:55:51.834: E/AndroidRuntime(3109): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
即将使用" TypefaceSingelton"避免性能下降
除了该程序使用以下代码:
private final Typeface FontTF;
@Override
public void onCreate(Bundle savedInstanceState) {
Typeface FontTF = TypefaceSingelton.getFont();