4

I have myself a toolbar and I want a custom font for my title but I don't get it to work.

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

I think I did it right but it doesn't do anything.

MrEngineer13
  • 38,642
  • 13
  • 74
  • 93
Laurenswuyts
  • 2,144
  • 4
  • 21
  • 39

1 Answers1

12

You can do it using a TextView inside Toolbar. Toolbar is just a 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>

And then get it programmatically:

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);
Catalina
  • 1,954
  • 1
  • 17
  • 25
Giorgio Antonioli
  • 15,771
  • 10
  • 45
  • 70