我想将自定义字体应用于 ActionBar 上显示的我的应用程序的标题。以前我没有使用任何支持库和这个解决方案:
int titleId = getResources().getIdentifier("action_bar_title", "id",
"android");
TextView yourTextView = (TextView) findViewById(titleId);
yourTextView.setTypeface(face);
对我来说效果很好。但现在我正在使用 Material 设计 SupportActionBar,这会抛出 NullPointerException。那么在使用AppCompat时如何改变ActionBar的字体呢?
最佳答案
假设您已经成功使用 AppCompat v22+ 的新工具栏 并且您正在您的 Activity 中导入 android.support.v7.widget.Toolbar。
所以在你的 OnCreate 上你应该已经有了
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
此时你几乎完成了:
导入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) {
}
关于android - 使用 AppCompat 时如何更改 ActionBar 标题字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27757373/