本文介绍了使用AppCompat时如何更改ActionBar标题字体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将自定义字体应用于显示在ActionBar上的应用程序的标题.以前我没有使用任何支持库和此解决方案:

I would like to apply custom font to the title of my app which is displayed on the ActionBar. Previously I didn't use any support library and this solution:

int titleId = getResources().getIdentifier("action_bar_title", "id",
                "android");
TextView yourTextView = (TextView) findViewById(titleId);
yourTextView.setTypeface(face);

对我来说很好.但是现在我使用的是材质设计SupportActionBar,这会引发NullPointerException.那么在使用AppCompat时如何更改ActionBar字体?

worked fine for me. But now I am using material design SupportActionBar and this throws NullPointerException. So how to change the ActionBar font when using AppCompat?

推荐答案

假定您已经成功使用AppCompat v22 +的新工具栏并且您正在活动中导入android.support.v7.widget.Toolbar.

Assuming you are already successfully using the new toolbar of AppCompat v22+and that you are importing android.support.v7.widget.Toolbar in your activity.

因此在OnCreate上您应该已经拥有

So on your OnCreate you should already have

toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

至此,您已经快完成了:

at this point you are almost done:

导入java.lang.reflect.field;

import java.lang.reflect.field;

并添加以下几行:

TextView yourTextView = null;
try {
    Field f = toolbar.getClass().getDeclaredField("mTitleTextView");
    f.setAccessible(true);
    yourTextView = (TextView) f.get(toolbar);
    yourTextView.setTypeface(face);
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}

这篇关于使用AppCompat时如何更改ActionBar标题字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 15:42