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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32398104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 12:28:47  来源:igfitidea点击:

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

javaandroidfontstoolbartitle

提问by anupam x

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?

我想为标题“你好”中的文本设置自定义字体。怎么做?

采纳答案by gmetax

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. So in your activity you can access the title like so:

这意味着您可以随意设置 TextView 的样式,因为它只是一个普通的 TextView。因此,在您的活动中,您可以像这样访问标题:

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

UPDATEdynamically 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);

回答by EminenT

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

回答by farukcankaya

Thank you @gmetax, it's a good point. It's bad to access textview for each activity. We have to write code below for each activity:

谢谢@gmetax,这是一个很好的观点。为每个活动访问 textview 是不好的。我们必须为每个活动在下面编写代码:

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

We've already bind toolbar and we've use toolbar.setTitle(). So, I extend Toolbar and override setTitle method like this:

我们已经绑定了工具栏并且我们已经使用了 toolbar.setTitle()。因此,我扩展 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");

回答by afathman

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. Instead, I used the following method to find the TextView:

我仍然想使用 Toolbars 标题方法,因此在 Toolbar xml 元素内添加自定义 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;
            }
        }
    }
}

回答by afathman

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. Instead, I used the following method to find the TextView:

我仍然想使用 Toolbars 标题方法(我也不想拥有自定义 Toolbar 类),因此在 Toolbar xml 元素内添加自定义 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;
            }
        }
    }
}

回答by arushe

  1. Placement of Fonts:

    • Firstly, download a .ttf file. My file is 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.
  2. Go to the java file of the activity whose font you have to customize. I customized mainActivity here.

     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); }
    
    
     }
    
  1. 字体的放置:

    • 首先,下载一个 .ttf 文件。我的文件是 Balker.ttf
    • 确保您有一个“资产”文件夹。如果没有,右键单击应用程序转到新建>文件夹>资产文件夹
    • 在资产文件夹中,创建一个新文件夹并将其命名为“字体”
    • 像我对 Balker.ttf 所做的那样,将您的文件放入“字体”文件夹中。
  2. 转到您必须自定义其字体的活动的 java 文件。我在这里自定义了 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); }
    
    
     }
    

回答by mohammad golche

This works for me

这对我有用

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

回答by Rainmaker

Since android.support.v7.appcompat 24.2Toolbarhas method setTitleTextAppearanceand you can set its font without external textview.

由于android.support.v7.appcompat 24.2Toolbarhas 方法setTitleTextAppearance,您可以在没有 external 的情况下设置其字体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);

回答by realpac

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

回答by sirvan alie

You can create fontsfolder 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 titleTextAppearancein toolbar to style you are defined.

您可以在最新版本的Android studio 3 中在res 目录下创建fonts文件夹。此后您必须在styles 中定义自定义样式,然后您必须使用工具栏中的titleTextAppearance来定义您定义的样式。

Stepslike below.

步骤如下。

1.Create fonts directory : res> Android Resource Directory> Resource type : fonts, and click on Okto create fonts directory(Android studio 3).

1.创建字体目录:res> Android Resource Directory> Resource type : fonts,然后点击Ok创建字体目录(Android studio 3)。

  1. Open styles.xmland make custom style like below

    <style name="**TextAppearance.TabsFont**" parent="**android:TextAppearance**">
        <item name="android:fontFamily">font/rmedium</item>
        <item name="android:textSize">18sp</item>
    </style>
    
  1. 打开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.

这是DONE。现在,如果您运行应用程序,您可以看到设置到工具栏的字体。