Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom font on toolbar in android [duplicate]

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.

like image 936
Laurenswuyts Avatar asked Dec 14 '22 15:12

Laurenswuyts


1 Answers

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);
like image 132
Giorgio Antonioli Avatar answered Dec 17 '22 05:12

Giorgio Antonioli