android中工具栏上的自定义字体

Lau*_*yts 4 android android-toolbar

我有自己的工具栏,我想为我的标题自定义字体,但我不能让它工作.

            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);
Run Code Online (Sandbox Code Playgroud)

我想我做得对,但它没有做任何事情.

Gio*_*oli 12

你可以用TextView里面做的Toolbar.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>
Run Code Online (Sandbox Code Playgroud)

然后以编程方式获取它:

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);
Run Code Online (Sandbox Code Playgroud)