Sarah Pöhler Sarah Pöhler - 2 months ago 13
Android Question

Custom Font for an Android App

I tried to add a custom font in my app. The method creating a typeface object and putting a font in it worked. Now I want to make a class for the custom font for having a cleaner code.

CustomFont class:

public class CustomFont extends AppCompatActivity {

private final Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/Slabo.ttf");

public CustomFont(TextView textView) {
textView.setTypeface(typeface);
}
}


and now I am trying to add this font to a 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

}
}


but if I run this project I get this exception:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.AssetManager android.content.Context.getAssets()' on a null object reference

Answer

first of all CustomFont should not be activity.It should be normal class.

public class CustomFont {

    private Typeface typeface;
    public CustomFont(Context context) {
        typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Slabo.ttf");
    }
    public void setFont(TextView textView) {
        textView.setTypeface(typeface);
    }
}

And call it from your MainActivity

customFont = new CustomFont(this);
customFont.setFont(textview);
Comments