SetSpan 在 ScrollingActivity Title 中不起作用

SetSpan not working in ScrollingActivity Title

我设法通过以下代码更改了 "normal" 活动中 AppBar 标题的字体:

setContentView(R.layout.activity_scrolling);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);        

    SpannableString s = new SpannableString("MyTitle");
    s.setSpan(new TypefaceSpan(this, "Britannic_Bold.ttf"), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    setTitle(s);

使用自定义 class TypefaceSpan:

public class TypefaceSpan extends MetricAffectingSpan {
/** An <code>LruCache</code> for previously loaded typefaces. */
private static LruCache<String, Typeface> sTypefaceCache =
        new LruCache<String, Typeface>(12);

private Typeface mTypeface;

/**
 * Load the {@link Typeface} and apply to a {@link Spannable}.
 */
public TypefaceSpan(Context context, String typefaceName) {
    mTypeface = sTypefaceCache.get(typefaceName);

    if (mTypeface == null) {
        mTypeface = Typeface.createFromAsset(context.getApplicationContext()
                .getAssets(), String.format("fonts/%s", typefaceName));

        // Cache the loaded Typeface
        sTypefaceCache.put(typefaceName, mTypeface);
    }
}

@Override
public void updateMeasureState(TextPaint p) {
    p.setTypeface(mTypeface);

    // Note: This flag is required for proper typeface rendering
    p.setFlags(p.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
}

@Override
public void updateDrawState(TextPaint tp) {
    tp.setTypeface(mTypeface);

    // Note: This flag is required for proper typeface rendering
    tp.setFlags(tp.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
}

}

但是,这在滚动 activity 中不起作用(由 Android Studio 创建)

滚动的标题 activity 不会更改其字体,但文本会按预期更改。

我已经尝试了很多,包括为工具栏标题创建样式,但它似乎不起作用。

有什么我可能监督的吗?

这里是滚动的XML-partactivity:

<android.support.design.widget.AppBarLayout
    android:id="@+id/app_bar"
    android:layout_width="match_parent"
    android:layout_height="@dimen/app_bar_height"
    android:fitsSystemWindows="true"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/toolbar_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        app:contentScrim="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>

经过反复试验,我找到了解决方案!

只需获取 CollapsedToolbarLayout 并调用 setCollapsedTitleTypeface(customFont) 和 setExpandedTitleTypeface(customFont)!

很有魅力! :)