0

我没有从创建新类中获得外部字体,我在其中定义了外部字体。

字体样式.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

请人纠正我:提前谢谢。

4

1 回答 1

2

首先,您需要将 Activity 上下文传递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;
  }
}

现在将 Activity 代码更改为为 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());
}
于 2013-02-08T05:40:24.687 回答