android 工具栏上的自定义字体

Custom font on toolbar in android

我自己有一个工具栏,我想为我的标题使用自定义字体,但我无法使用它。

            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            SpannableString title = new SpannableString(getResources().getString(R.string.app_name));
            title.setSpan(Typeface.createFromAsset(getAssets(), "KeepCalm-Medium.ttf"), 0, title.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            toolbar.setTitle(title);
            setSupportActionBar(toolbar);

我认为我做对了,但它什么也没做。

您可以在 Toolbar 中使用 TextView 来完成。 Toolbar 只是一个 ViewGroup:

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_height="wrap_content"
    android:layout_width="match_parent">

     <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Toolbar Title"
        android:layout_gravity="center"
        android:id="@+id/toolbar_title" />

</android.support.v7.widget.Toolbar>

然后以编程方式获取它:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TextView toolbarTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "KeepCalm-Medium.ttf");
toolbarTitle.setTypeface(myTypeface);