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