我正在尝试设置自定义字体,但始终会收到textview
为空的错误。这是我的代码:
int titleId = getResources().getIdentifier("action_bar_title", "id", "android");
TextView yourTextView = (TextView) findViewById(titleId);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/barrett_normal.ttf");
获取以下错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setTypeface(android.graphics.Typeface)' on a null object reference
这是我的onCreate()
方法:
@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());
}
答案 0 :(得分:1)
试试这种方式
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);
检查here TypefaceSpan