How to change the app title source?

Asked

Viewed 1,423 times

1

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

2 answers

4


One of the new features made available from Android is the possibility of use fonts as Resources.

Now, in addition to the traditional Resources, it is possible to add a folder named fonts inside the briefcase res.
For each of the source files placed in this folder entries are created in the R class, allowing them to be referenced like any other Resource, via @font/myfont or R.font.myfont.

The use of this feature is available from version 3 of Android Studio and requires, as a minimum:

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

With this configuration and having its source "customized" inside the folder /res/fonts, change the file values/Styles.xml as described in this reply to the question How to change the font color of the application title.

Inside the style statement MyActionBarTitleText use

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

to indicate the name of the source to be used in the app title.

2

To Toolbar is a 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 done, you need to remove the current title from your Toolbar, not to generate conflicts. Use the method: setDisplayShowTitleEnabled(boolean showTitle)

Thus remaining:

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

Then change the typeFace of TextView which is in the Toolbar. Do it:

// 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 don’t want to use another View within the Toolbar, you can change the source of it by checking each Child that the Toolbar has, until you find a Textview.

Since Toolbar is a Viewgroup, it means that it can contain other Views within it, that is, Textview is there, but we cannot access directly, so we do so:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.