安卓工具栏上使用自定义字体

4
我有一个工具栏,想要为我的标题使用自定义字体,但我无法使其生效。
            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);

我认为我做得没错,但它什么也没做。

1个回答

12

您可以使用 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);

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