android - 使用 AppCompat 时如何更改 ActionBar 标题字体

标签 android android-layout android-actionbar android-actionbar-compat android-fonts

我想将自定义字体应用于 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/

相关文章:

java - 如何在android中使用计时器设置进度条?

android - 跨多个 Android 应用程序保留登录 session

android - 如何制作结束学分页面 - 动画 TableLayout 而不会在显示尺寸处被切割

android - 如何在 Android 中将 Imageview 置于 Listview 下方?

Android:旋转动画完成动画后恢复到真实状态?

android - 以 root 身份运行 NanoHttpd

android - 对象标题未在开放图表(时间轴)中更新

android - 如何在 Android 中滚动 ListView 时隐藏 ActionBar?

android - 如何删除或更改 SearchView actionBar 中的 searchview 图标?

android - 使用 fragment 处理 setDisplayHomeAsUpEnabled