Reputation: 4157
I am trying to set custom font but always getting error that textview
is null. Here is my code:
int titleId = getResources().getIdentifier("action_bar_title", "id", "android");
TextView yourTextView = (TextView) findViewById(titleId);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/barrett_normal.ttf");
Getting following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setTypeface(android.graphics.Typeface)' on a null object reference
This is my onCreate()
method:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayShowCustomEnabled(true);
int titleId = getResources().getIdentifier("action_bar_title", "id", "android");
tv = (TextView) findViewById(titleId);
tf = Typeface.createFromAsset(getAssets(), "fonts/barrett_normal.ttf");
tv.setTypeface(tf);
} catch (Exception e) {
e.printStackTrace();
}
setActionBarTitle(this.getTitle());
}
Upvotes: 0
Views: 235
Reputation: 13555
Try this way
SpannableString s = new SpannableString("My Title");
s.setSpan(new TypefaceSpan(this, "MyTypeface.otf"), 0, s.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// Update the action bar title with the TypefaceSpan instance
ActionBar actionBar = getActionBar();
actionBar.setTitle(s);
Check here for TypefaceSpan
Upvotes: 1