Search code examples
javaandroidfontstoolbartitle

How to set a custom font to the title in toolbar android


I am doing this:

toolbar = (Toolbar) findViewById(com.sports.unity.R.id.tool_bar);
setSupportActionBar(toolbar);
setTitle("hello");

I want to set a custom font for the text here in the title "hello". How to do that?


Solution

  • Update 2018 (kotlin version)

    fun Toolbar.changeToolbarFont(){
        for (i in 0 until childCount) {
            val view = getChildAt(i)
            if (view is TextView && view.text == title) {
                view.typeface = Typeface.createFromAsset(view.context.assets, "fonts/customFont")
                break
            }
        }
    }
    

    and use it like that toolBar.changeToolbarFont()

    old-post

    To use a custom title in your Toolbar all you need to do is remember is that Toolbar is just a fancy ViewGroup so you can add a custom title like so:

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar_top"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:minHeight="?attr/actionBarSize"
        android:background="@color/action_bar_bkgnd"
        app:theme="@style/ToolBarTheme" >
    
    
         <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Toolbar Title"
            android:layout_gravity="center"
            android:id="@+id/toolbar_title" />
    
    
        </android.support.v7.widget.Toolbar>
    

    This means that you can style the TextView however you would like because it's just a regular TextView. So in your activity you can access the title like so:

    Toolbar toolbarTop = (Toolbar) findViewById(R.id.toolbar_top);
    TextView mTitle = (TextView) toolbarTop.findViewById(R.id.toolbar_title);
    

    And then:

    Typeface khandBold = Typeface.createFromAsset(BalrogApplication.getApplication().getAssets(), "fonts/Khand-bold.ttf");
    
    mTitle.setTypeface(khandBold);
    

    UPDATE dynamically version

    public static void changeToolbarFont(Toolbar toolbar, Activity context) {
        for (int i = 0; i < toolbar.getChildCount(); i++) {
            View view = toolbar.getChildAt(i);
            if (view instanceof TextView) {
                TextView tv = (TextView) view;
                if (tv.getText().equals(toolbar.getTitle())) {
                    applyFont(tv, context);
                    break;
                }
            }
        }
    }
    
    public static void applyFont(TextView tv, Activity context) {
        tv.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/customFont"));
    }
    

    and use it like that

    changeToolbarFont(findViewById(R.id.app_bar), this);