简体   繁体   English

如何为工具栏android中的标题设置自定义字体

[英]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?怎么做?

Since android.support.v7.appcompat 24.2 Toolbar has method setTitleTextAppearance and you can set its font without external textview .由于android.support.v7.appcompat 24.2 Toolbar有方法setTitleTextAppearance并且您可以在没有外部textview情况下设置其字体。

create new style in styles.xml在styles.xml 中创建新样式

<style name="RobotoBoldTextAppearance">
        <item name="android:fontFamily">@font/roboto_condensed_bold</item>
</style>

and use it并使用它

mToolbar.setTitleTextAppearance(this, R.style.RobotoBoldTextAppearance);

Update 2018 (kotlin version) 2018 年更新(kotlin 版本)

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()并像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:要在 Toolbar 中使用自定义标题,您需要做的就是记住 Toolbar 只是一个奇特的 ViewGroup,因此您可以像这样添加自定义标题:

<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.这意味着您可以随意设置 TextView 的样式,因为它只是一个普通的 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);

I still wanted to use the Toolbars title methods (nor did I want to have a custom Toolbar class), so adding in the custom TextView inside of the Toolbar xml element didn't work for me.我仍然想使用 Toolbars 标题方法(我也不想拥有自定义 Toolbar 类),因此在 Toolbar xml 元素内添加自定义 TextView 对我不起作用。 Instead, I used the following method to find the TextView:相反,我使用以下方法来查找 TextView:

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

You can do this using just themes:您可以仅使用主题来执行此操作:

I wrote an article outlining the full solution. 我写了一篇文章概述了完整的解决方案。 Here are the basics:以下是基础知识:

1) Define a theme in styles.xml : 1)在styles.xml定义一个主题:

<style name="ToolbarTheme" parent="ThemeOverlay.AppCompat.Light">
    <item name="android:fontFamily">@font/fancy-font</item>
</style>

2) Set that theme in your Toolbar s layout: 2)在您的Toolbar布局中设置该主题:

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="@color/colorPrimary"
    android:theme="@style/ToolbarTheme"/>

This assumes that you have a .ttf file stored in res/font :这假设您有一个.ttf文件存储在res/font

带有字体的资源目录

You can create fonts folder under res directory in last version Android studio 3 .After this you must be define custom style in styles , and after this , you must be use titleTextAppearance in toolbar to style you are defined.您可以在最新版本的Android studio 3 中在res 目录下创建fonts文件夹。此后您必须在styles 中定义自定义样式,然后您必须使用工具栏中的titleTextAppearance来定义您定义的样式。

Steps like below.步骤如下。

1. Create fonts directory : res > Android Resource Directory > Resource type : fonts , and click on Ok to create fonts directory(Android studio 3). 1.创建字体目录: res > Android Resource Directory > Resource type : fonts ,点击确定创建字体目录(Android studio 3)。

  1. Open styles.xml and make custom style like below打开styles.xml并制作如下自定义样式

    <style name="**TextAppearance.TabsFont**" parent="**android:TextAppearance**"> <item name="android:fontFamily">font/rmedium</item> <item name="android:textSize">18sp</item> </style>

3.Now open layout and add app:titleTextAppearance="@style/TextAppearance.TabsFont" to Toolbar tag, like below. 3.现在打开布局并将app:titleTextAppearance="@style/TextAppearance.TabsFont" 添加到工具栏标签,如下所示。

<android.support.v7.widget.Toolbar

    android:id="@+id/toolbarMain"
    app:title="@string/time_amp_date"
    app:titleTextAppearance="@style/TextAppearance.TabsFont"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="@color/colorPrimary"
    android:theme="@style/AppTheme"
    app:elevation="2dp" />

That's DONE .大功告成 Now if you running app, you can see font set to your toolbar.现在,如果您运行应用程序,您可以看到设置到工具栏的字体。

  1. Placement of Fonts:字体的放置:

    • Firstly, download a .ttf file.首先,下载一个 .ttf 文件。 My file is Balker.ttf我的文件是 Balker.ttf
    • make sure that you have got an "assets" folder.确保您有一个“资产”文件夹。 If there is none, right click over app go to New>Folder>assets Folder如果没有,右键单击应用程序转到新建>文件夹>资产文件夹
    • In assets folder, create a new folder and name it 'font'在资产文件夹中,创建一个新文件夹并将其命名为“字体”
    • Put your file, as I did with Balker.ttf, into the 'font' folder.像我对 Balker.ttf 所做的那样,将您的文件放入“字体”文件夹中。
  2. Go to the java file of the activity whose font you have to customize.转到您必须自定义其字体的活动的 java 文件。 I customized mainActivity here.我在这里自定义了 mainActivity。

     for(int i = 0; i < toolbar.getChildCount(); i++) { View view = toolbar.getChildAt(i); if(view instanceof TextView) { TextView textView = (TextView) view; Typeface myCustomFont=Typeface.createFromAsset(getAssets(),"font/Balker.ttf"); textView.setTypeface(myCustomFont); } }

You can use this simple method to set custom font to toolbar title.您可以使用这种简单的方法将自定义字体设置为工具栏标题。

 Toolbar   toolbar = (Toolbar) findViewById(com.sports.unity.R.id.tool_bar);
        TextView tv = getToolBarTextView();
        tv.settext("Hello");

private TextView getToolBarTextView() {
        TextView titleTextView = null;

        try {
            Field f = mToolBar.getClass().getDeclaredField("mTitleTextView");
            f.setAccessible(true);
            titleTextView = (TextView) f.get(mToolBar);

     Typeface font = Typeface.createFromAsset(getApplicationContext().getAssets(),"fonts/mfont.ttf");
    titleTextView.setTypeface(font);

        } catch (NoSuchFieldException e) {
        } catch (IllegalAccessException e) {
        }
        return titleTextView;
    }

This works for me这对我有用

typeFace= Typeface.createFromAsset(this.getAssets(), "fonts/myfont.ttf");
((TextView)toolbar.getChildAt(1)).setTypeface(typeFace);

I searched for this question as well, and this was one of the first answers that came up.我也搜索了这个问题,这是第一个出现的答案。 I'll add my solution since the one given here can be counted as a bit outdated (keep in mind it would work nonetheless).我将添加我的解决方案,因为这里给出的解决方案可以算作有点过时(请记住,它仍然可以工作)。

Since Android now supports custom fonts, there's no reason to assign fonts in Java, it can be done while making the XML file itself.由于 Android 现在支持自定义字体,因此没有理由在 Java 中分配字体,可以在制作 XML 文件本身时完成。

First, in your layout file, add a custom Toolbar (you can set the text size here itself)首先,在您的布局文件中,添加一个自定义工具栏(您可以在此处自行设置文本大小)

<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/primary">
        <TextView
            android:id="@+id/toolbar_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/signup"
            android:textSize="22sp" />
    </android.support.v7.widget.Toolbar>

Then, go to the design tab of your XML file, and select the text on the toolbar.然后,转到 XML 文件的设计选项卡,并选择工具栏上的文本。

第1步

Select the option of fontFamily and select the font you want under the given options.选择fontFamily的选项,在给定的选项下选择你想要的字体。 If it is not given, you can search for more fonts.如果没有给出,您可以搜索更多字体。

第2步

Search for the font you want and select it.搜索您想要的字体并选择它。 Your font gets changed.你的字体变了。

第 3 步

Your XML file now will reflect the font you added, there will be an attribute named android:fontFamily您的 XML 文件现在将反映您添加的字体,将有一个名为android:fontFamily的属性

<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/primary">
        <TextView
            android:id="@+id/toolbar_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fontFamily="@font/roboto_slab"
            android:text="@string/signup"
            android:textColor="@color/secondaryBackground"
            android:textSize="22sp" />
    </android.support.v7.widget.Toolbar>

Hope this helped.希望这有帮助。

No need to use external textview if you only want to change the font of toolbar title because android.support.v7.appcompat 24.2 Toolbar has method setTitleTextAppearance and you can set its font like below.如果您只想更改工具栏标题的字体,则无需使用外部文本视图,因为android.support.v7.appcompat 24.2 Toolbar具有setTitleTextAppearance方法,您可以如下设置其字体。

create a new style in styles.xml在styles.xml 中创建一个新样式

<style name="CamptonBookTextAppearance">
     <item name="android:fontFamily">@font/campton_book</item>
</style>

and use it并使用它

mToolbar.setTitleTextAppearance(this, R.style.CamptonBookTextAppearance);

If anyone has an issue of getting multiple toolbar title (one default and one that you set ) for xml:如果有人遇到为 xml 获取多个工具栏标题(一个默认值和您设置的一个)的问题:

  <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/app_name"
                android:layout_gravity="left"
                android:id="@+id/toolbar_title"
                android:textSize="20sp"/>

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

then do this:然后这样做:

        getSupportActionBar().setTitle(null);//Set the default to null
        typeFace= Typeface.createFromAsset(getAssets(), "fonts/Raleway-Light.ttf");
        toolbarTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
        toolbarTitle.setTypeface(typeFace);

I made a binding adapter for this purpose.为此,我制作了一个绑定适配器。

public class FontBindingAdapter
{
    @BindingAdapter({"font"})
    public static void setFont(Toolbar toolbar, String font)
    {
        for (int i = 0; i < toolbar.getChildCount(); i++) {
            if (toolbar.getChildAt(i) instanceof AppCompatTextView) {
                UIUtil.setFont(font, (AppCompatTextView) toolbar.getChildAt(i));
            }
        }
    }
}

Then use it like:然后像这样使用它:

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="@color/green"
                app:font="@{`LatoRegular`}"
                app:title="@string/setup_favorites"
                app:titleTextColor="@color/white"/>

Thank you @gmetax, it's a good point.谢谢@gmetax,这是一个很好的观点。 It's bad to access textview for each activity.为每个活动访问 textview 是不好的。 We have to write code below for each activity:我们必须为每个活动在下面编写代码:

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

We've already bind toolbar and we've use toolbar.setTitle().我们已经绑定了工具栏并且我们已经使用了 toolbar.setTitle()。 So, I extend Toolbar and override setTitle method like this:因此,我扩展 Toolbar 并覆盖 setTitle 方法,如下所示:

@Override
public void setTitle(CharSequence title) {
    super.setTitle("");
    mTitle = (TextView) findViewById(R.id.toolbar_title);
    if (mTitle != null) {
        if (!TextUtils.isEmpty(title)) {
            mTitle.setText(title);
        }
    }
}

(Of course, custom font should be setted in CustomTextView class.setTypeface) Now, we can use just like this: (当然,自定义字体应该在CustomTextView class.setTypeface中设置) 现在,我们可以这样使用:

toolbar.setTitle("bla bla");

I still wanted to use the Toolbars title methods, so adding in the custom TextView inside of the Toolbar xml element didn't work for me.我仍然想使用 Toolbars 标题方法,因此在 Toolbar xml 元素内添加自定义 TextView 对我不起作用。 Instead, I used the following method to find the TextView:相反,我使用以下方法来查找 TextView:

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

If you are using google fonts (ie. Open Sans) you can add TextView as a child of your Toolbar like this如果您使用的是谷歌字体(即 Open Sans),您可以像这样将 TextView 添加为工具栏的子项

<android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/app_name"
                android:fontFamily="@font/open_sans"/>

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

and then just set fontFamily property for your TextView in Attributes menu (More Fonts option at the end of the dropdown list)然后在“属性”菜单中为您的 TextView 设置 fontFamily 属性(下拉列表末尾的“更多字体”选项)

android:fontFamily="@font/open_sans

Just add textapperance in your toolbar xml no need to custumization:-只需在工具栏 xml 中添加 textapperance 无需自定义:-

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:gravity="center"
android:minHeight="?attr/actionBarSize"
**app:titleTextAppearance="@font/montserrat_regular"**// apply your font
app:titleTextColor="@android:color/white" />

You can Use Custom font of toolbar programmatically Like this您可以像这样以编程方式使用工具栏的自定义字体

1) first Create sub dir fonts in asset folder 1)首先在资产文件夹中创建子目录字体

2) Add your font files in the fonts folder. 2) 在 fonts 文件夹中添加您的字体文件。

  toolbar.setTitle("Welcome");
        Typeface fromAsset  = Typeface.createFromAsset(getAssets(),"fonts/OpenSans-Light.ttf");
        ((TextView)toolbar.getChildAt(1)).setTypeface(fromAsset); 

1st create第一次创建

  <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:titleTextAppearance="@style/DancingWhite"
            app:popupTheme="@style/AppTheme.PopupOverlay"
            >


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

2nd第二名

your activity you can access the title like so:您的活动,您可以像这样访问标题:

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

 Typeface font = Typeface.createFromAsset(getAssets(), "Mukta- Regular.ttf");

  mTitle.setTypeface(font);

just download what font you want to show in title and move it under res->font folder and create a file over there fontfamily只需下载您想在标题中显示的字体并将其移动到 res->font 文件夹下并在那里创建一个文件 fontfamily

<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
<font
    android:fontStyle="normal"
    android:fontWeight="400"
    android:font="@font/futura_book" />


<font
    android:fontStyle="normal"
    android:fontWeight="400"
    android:font="@font/your font file name" />




</font-family>

now add fontfamily="your downloaded font family name like a.ttf" in your xml file thats it现在在您的 xml 文件中添加 fontfamily="您下载的字体系列名称,如 a.ttf"

Download the custom font and keep it in font folder inside the res folder.下载自定义字体并将其保存在 res 文件夹内的字体文件夹中。 As Toolbar is a viewGroup we can place the textView inside the Toolbar and use as follow由于 Toolbar 是一个 viewGroup,我们可以将 textView 放置在 Toolbar 内并使用如下

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:elevation="0dp">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        >
        <TextView
            android:id="@+id/toolbar_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Toolbar"
            android:gravity="center"
            android:fontFamily="@font/roboto_regular" <--- custom font
            android:textColor="@color/white"
            android:textStyle="bold"
            android:textAppearance="@style/Base.TextAppearance.Widget.AppCompat.Toolbar.Title"
            />

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


</android.support.design.widget.AppBarLayout>

This method is also used to make font BOLD .此方法也用于制作字体BOLD

Two way you can do custom font on toolbar title两种方法可以在工具栏标题上自定义字体

Step : 1 [ Static Method ]步骤:1 [静态方法]

1) Define a theme in styles.xml : 1)在styles.xml中定义一个主题:

  <style name="ToolbarTheme" parent="ThemeOverlay.AppCompat.Light">
      <item name="android:fontFamily">@font/ubuntu</item>
  </style>

2) Set that theme in your Toolbar's layout: 2) 在工具栏的布局中设置该主题:

   <android.support.v7.widget.Toolbar
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:id="@+id/toolbar"
     android:layout_width="match_parent"
     android:layout_height="?attr/actionBarSize"
     android:background="@color/colorPrimary"
     android:theme="@style/ToolbarTheme"/>

Step 2 : [ Dynamic ]第 2 步:[动态]

Kotlin科特林

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

then use it like然后像这样使用它

   toolBar.titleFont()

I just add my fonts to the font folder I made in res along with the other fonts, then I made a custom XML file for the bar.我只是将我的字体与其他字体一起添加到我在res的字体文件夹中,然后我为该栏创建了一个自定义 XML 文件。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">

<TextView
    android:id="@+id/action_bar_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/app_name"
    android:textSize="30sp"
    android:fontFamily="@font/yourfont"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"/></LinearLayout>

Then, I added this to my MainActivity然后,我将此添加到我的MainActivity

getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    getSupportActionBar().setDisplayShowCustomEnabled(true);
    getSupportActionBar().setCustomView(R.layout.your_xml_file);

Both OTF and TTF works OTF和TTF都有效

The best answer really is the best.最好的答案确实是最好的。 If you want to increase (adjust the font size) and change the colour then update your style like this:如果您想增加(调整字体大小)并更改颜色,请像这样更新您的样式:

<style name="NexaBoldToolbar">
    <item name="android:fontFamily">@font/nexabold</item>
    <item name="android:textSize">18sp</item>
    <item name="android:textColor">@color/fullWhite</item>
</style>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM