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

14

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

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

以前我使用时一切正常。但现在我正在使用 Material Design 的 SupportActionBar,这会抛出 NullPointerException。那么,在使用 AppCompat 时如何更改 ActionBar 字体?


1
我认为这个回答可以帮到你:https://dev59.com/N2oy5IYBdhLWcg3wWsw_#15181195 - Nickolay Savchenko
@user27799 谢谢,这篇帖子解决了我的问题。如果有人遇到类似的问题,只需使用链接帖子中的方法,它可以很好地支持库v-21。 - fragon
这里有解决方案,自定义Actionbar设计 - Karthikeyan
3个回答

6
假设您已成功使用 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) {
}

1
适用于我。谢谢。 - QuantumTiger

2

使用工具栏代替操作栏。请按以下步骤添加工具栏: 1. 将应用程序主题更改为Theme.AppCompat.Light.NoActionBar 2. 从文件菜单中进入项目结构,进入库依赖项,添加设计库并同步您的项目。 3. 进入要显示操作栏的布局,并编写以下代码:

<android.support.v7.widget.Toolbar
    android:id="@+id/mytoolbar"
    android:layout_width="match_parent"
    android:layout_height="56dp"
    android:background="@color/pccolor"
    android:title="Services"
    app:titleTextAppearance="@style/Toolbar.TitleText"
    android:elevation="4dp">
  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Toolbar Title"
    android:layout_gravity="center"
    android:id="@+id/toolbar_title" />
</android.support.v7.widget.Toolbar>

4.在Activity中,按照以下方式编写:

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

自定义标题字体:

fontPath = "Fonts/Roboto-Light.ttf";
    Typeface tf = Typeface.createFromAsset(getActivity().getAssets(), fontPath);

TextView tv_ins=(TextView)FindViewById(R.id.toolbar_title);
 tv_ins.setText("mytitle");
tv_ins.setTypeface(tf);

试试这个,希望能对你有所帮助,如果有任何错误,请告诉我。


-2

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接