How to change app title font?

1

I want to change the font of the app title with a custom font, the font is already in the assets/fonts folder.

    
asked by anonymous 13.05.2017 / 17:12

2 answers

3

One of the new features made available from Android is the ability to use fonts as resources .

Now, in addition to the traditional resources folder, you can add a folder named fonts inside the res folder. For each of the font files placed in this folder, entries in the R class are created, allowing them to be referenced like any other resource , via @font/myfont or R.font.myfont .

Using this feature is available from version 3 of Android Studio and requires at least:

  • compileSdkVersion 26
  • buildToolsVersion "26.0.0"
  • minSdkVersion 26 or minSdkVersion 14 com appcompat-v7: 26.0.0-beta2

With this configuration and having your font "custom" inside the / res / fonts folder, change the values / styles.xml file as described in answer to the question How to change the font color of the application title .

Within the statement of style MyActionBarTitleText use

<item name="android:fontFamily">@font/sua_font</item>

to indicate the font name to use in the app title.

    
09.06.2017 / 16:18
2

The Toolbar is ViewGroup , this means that you can group other Views within it. Doing so:

<android.support.v7.widget.Toolbar
    android:id="@+id/app_toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="#fff"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView
        android:id="@+id/app_toolbar_title"
        android:height="wrap_content"
        android:width="wrap_content"/>

</android.support.v7.widget.Toolbar>

Once you've done this, you need to remove the current title from your Toolbar , not to generate conflicts. Use the method: setDisplayShowTitleEnabled(boolean showTitle)

Looking like this:

setSupportActionBar(mToolbar)
getSupportActionBar().setDisplayShowTitleEnabled(false)

Then change the typeFace of TextView that is in Toolbar . Do this:

// findView
Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/font.ttf"); // não esqueça do .ttf

toolbarTitle = (TextView) mToolbar.findViewById(R.id.app_toolbar_title)
toolbarTitle.setTypeface(tf)

If you do not want to use another View within Toolbar , you can change the source of it by checking every child that the Toolbar has, until you find a TextView .

As the Toolbar is a ViewGroup, it means that it can contain other View within it, that is, the TextView is there, but we can not access it directly, so we do this:

for (int i = 0; i < mToolbar.getChildCount(); i++) {
    View v = mToolbar.getChildAt(i)
    if (v instanceof TextView || v instanceof AppCompatTextView)
        addTypeFace(v) break;
}

private void addTypeFace(View v) {
    // createFromAsset...
    v.setTypeface(typeface)
}
    
13.05.2017 / 20:01