在Android中没有获取外部字体

时间:2013-02-08 05:33:08

标签: android fonts

我没有从创建新类获取外部字体,我定义了外部字体。

FontStyle.Java

public class FontStyle extends Activity{
    public final static String roboto_regular = "fonts/roboto_regular.ttf";
    public Typeface font_roboto_regular = Typeface.createFromAsset(getAssets(),
        roboto_regular);

}

MainActivity.Java

public class MainActivity extends Activity {
FontStyle font_style;
  @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
            fontStyling();
    }

   private void fontStyling() {
   TextView test= (TextView) findViewById(R.id.tv_test);
   test.setTypeface(font_style.font_roboto_regular );
}

我收到此错误或logcat:

 java.lang.RuntimeException: Unable to start activity  ComponentInfo{com.test/com.test.MainActivity}: java.lang.NullPointerException
请男士纠正我:提前谢谢。

1 个答案:

答案 0 :(得分:2)

首先,您需要在FontStyle中传递活动上下文以访问getAssets方法。如果FontStyle不是Activity,则无需将Activity扩展到它。将FontStyle类更改为:

public class FontStyle {
Context context;
public final static String roboto_regular = "fonts/roboto_regular.ttf";
public FontStyle(Context context){
 this.context=context;
}
  public Typeface getTtypeface(){
     Typeface font_roboto_regular = 
        Typeface.createFromAsset(context.getAssets(),roboto_regular);

    return font_roboto_regular;
  }
}

现在更改活动代码以设置TextView的自定义字体:

public class MainActivity extends Activity {
FontStyle font_style;
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        font_style=new FontStyle(MainActivity.this);
        fontStyling();
    }

private void fontStyling() {
TextView test= (TextView) findViewById(R.id.tv_test);
test.setTypeface(font_style.getTtypeface());
}