【问题标题】:How to change ActionBar title font when using AppCompat使用 AppCompat 时如何更改 ActionBar 标题字体
【发布时间】:2015-03-01 16:23:30
【问题描述】:

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

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

对我来说效果很好。但是现在我正在使用材料设计 SupportActionBar,这会引发 NullPointerException。那么在使用 AppCompat 时如何改变 ActionBar 字体呢?

【问题讨论】:

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


【解决方案1】:

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

【讨论】:

  • 为我工作。谢谢
【解决方案2】:

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

<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);

试试这个希望对你有帮助,如果有什么问题请告诉我。

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2016-01-06
      • 2015-01-08
      • 2015-06-02
      • 2017-07-08
      • 1970-01-01
      • 1970-01-01
      • 2014-05-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多