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

fra*_*gon 14 android android-layout android-fonts android-actionbar android-actionbar-compat

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

int titleId = getResources().getIdentifier("action_bar_title", "id",
                "android");
TextView yourTextView = (TextView) findViewById(titleId);
yourTextView.setTypeface(face);
Run Code Online (Sandbox Code Playgroud)

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

Dan*_* D. 6

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

所以你的OnCreate应该已经有了

toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Run Code Online (Sandbox Code Playgroud)

在这一点上,你差不多完成了:

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) {
}
Run Code Online (Sandbox Code Playgroud)


小智 -2

准备自定义布局,将文本视图放入action_bar_layout中,然后调用 actionbar.setcustomlayout()