我試圖在我的應用程序中添加自定義字體。創建typeface
對象並在其中放置字體的方法起作用。現在我想爲自定義字體制作一個更清晰的代碼。Android應用程序的自定義字體
CustomFont.java
public class CustomFont extends AppCompatActivity {
private final Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/Slabo.ttf");
public CustomFont(TextView textView) {
textView.setTypeface(typeface);
}
}
,現在我想這種字體添加到textview
:
public class MainActivity extends AppCompatActivity {
private Typeface typeface;
private CustomFont customFont;
private TextView textview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//typeface = Typeface.createFromAsset(getAssets(), "fonts/Slabo.ttf"); // works
textview = (TextView) findViewById(R.id.textviewTest);
//textview.setTypeface(typeface); // works
customFont = new CustomFont(textview); // does not work
}
}
,但如果我跑這個項目,我得到這個異常:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.AssetManager android.content.Context.getAssets()' on a null object reference
謝謝你這個作品! :) 你是最棒的! –