Reputation: 25
I am not getting external font, from creating new class, where i defined external font.
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);
}
and 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 );
}
I am getting this error or logcat:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test/com.test.MainActivity}: java.lang.NullPointerException
please guy correct me: thanks in advance.
Upvotes: 0
Views: 123
Reputation: 132982
first you will need to pass Activity context in FontStyle
to access getAssets
method. if FontStyle is not an Activity then no need to extends Activity to it. change your FontStyle class as:
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;
}
}
Now change Activity code as to set Custom font for 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());
}
Upvotes: 2