简体   繁体   English

无法使用自定义字体设置操作栏标题

[英]Unable to set action bar title with custom font

I am trying to set custom font but always getting error that textview is null. 我正在尝试设置自定义字体,但总是收到textview为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: 这是我的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());
    }

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 在此处检查TypefaceSpan

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM