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

时间:2016-03-24 07:23:32

标签: android nullpointerexception android-actionbar textview android-assets

我正在尝试设置自定义字体,但始终会收到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());
    }

1 个答案:

答案 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

相关问题