繁体   English   中英

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

[英]How to set a custom font to the title in toolbar android

我正在这样做:

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

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

由于android.support.v7.appcompat 24.2 Toolbar有方法setTitleTextAppearance并且您可以在没有外部textview情况下设置其字体。

在styles.xml 中创建新样式

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

并使用它

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

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

并像toolBar.changeToolbarFont()一样使用它

旧帖

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

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

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

进而:

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

mTitle.setTypeface(khandBold);

动态更新版本

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

并像那样使用它

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

我仍然想使用 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;
            }
        }
    }
}

您可以仅使用主题来执行此操作:

我写了一篇文章概述了完整的解决方案。 以下是基础知识:

1)在styles.xml定义一个主题:

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

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

这假设您有一个.ttf文件存储在res/font

带有字体的资源目录

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

步骤如下。

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

  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.现在打开布局并将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" />

大功告成 现在,如果您运行应用程序,您可以看到设置到工具栏的字体。

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

您可以使用这种简单的方法将自定义字体设置为工具栏标题。

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

这对我有用

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

我也搜索了这个问题,这是第一个出现的答案。 我将添加我的解决方案,因为这里给出的解决方案可以算作有点过时(请记住,它仍然可以工作)。

由于 Android 现在支持自定义字体,因此没有理由在 Java 中分配字体,可以在制作 XML 文件本身时完成。

首先,在您的布局文件中,添加一个自定义工具栏(您可以在此处自行设置文本大小)

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

然后,转到 XML 文件的设计选项卡,并选择工具栏上的文本。

第1步

选择fontFamily的选项,在给定的选项下选择你想要的字体。 如果没有给出,您可以搜索更多字体。

第2步

搜索您想要的字体并选择它。 你的字体变了。

第 3 步

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

希望这有帮助。

如果您只想更改工具栏标题的字体,则无需使用外部文本视图,因为android.support.v7.appcompat 24.2 Toolbar具有setTitleTextAppearance方法,您可以如下设置其字体。

在styles.xml 中创建一个新样式

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

并使用它

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

如果有人遇到为 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>

然后这样做:

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

为此,我制作了一个绑定适配器。

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

然后像这样使用它:

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

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

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

我们已经绑定了工具栏并且我们已经使用了 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);
        }
    }
}

(当然,自定义字体应该在CustomTextView class.setTypeface中设置) 现在,我们可以这样使用:

toolbar.setTitle("bla bla");

我仍然想使用 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;
            }
        }
    }
}

如果您使用的是谷歌字体(即 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>

然后在“属性”菜单中为您的 TextView 设置 fontFamily 属性(下拉列表末尾的“更多字体”选项)

android:fontFamily="@font/open_sans

只需在工具栏 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" />

您可以像这样以编程方式使用工具栏的自定义字体

1)首先在资产文件夹中创建子目录字体

2) 在 fonts 文件夹中添加您的字体文件。

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

第一次创建

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

第二名

您的活动,您可以像这样访问标题:

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

只需下载您想在标题中显示的字体并将其移动到 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>

现在在您的 xml 文件中添加 fontfamily="您下载的字体系列名称,如 a.ttf"

下载自定义字体并将其保存在 res 文件夹内的字体文件夹中。 由于 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>

此方法也用于制作字体BOLD

两种方法可以在工具栏标题上自定义字体

步骤:1 [静态方法]

1)在styles.xml中定义一个主题:

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

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

第 2 步:[动态]

科特林

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

然后像这样使用它

   toolBar.titleFont()

我只是将我的字体与其他字体一起添加到我在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>

然后,我将此添加到我的MainActivity

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

OTF和TTF都有效

最好的答案确实是最好的。 如果您想增加(调整字体大小)并更改颜色,请像这样更新您的样式:

<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