我想将自定义字体应用于 ActionBar 上显示的应用程序标题。以前我没有使用任何支持库和这个解决方案:
int titleId = getResources().getIdentifier("action_bar_title", "id",
"android");
TextView yourTextView = (TextView) findViewById(titleId);
yourTextView.setTypeface(face);
对我来说效果很好。但现在我使用材料设计SupportActionBar,这会引发NullPointerException。那么使用AppCompat时如何更改ActionBar字体呢?
假设您已经成功使用 AppCompat v22+ 的新工具栏
并且您正在活动中导入 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) {
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)