Android的工具栏中心的标题和自定义字体自定义、工具栏、字体、标题

2023-09-11 12:34:29 作者:萱草

我试图找出正确的方式来使用自定义字体工具栏标题和居中工具栏(客户要求)。

I'm trying to figure out the right way to use a custom font for the toolbar title, and center it in the toolbar (client requirement).

目前,我使用的是旧的好动作条,而我设置了标题为空值,并且使用setCustomView把我的自定义字体的TextView使用ActionBar.LayoutParams居中。

At the moment, i'm using the good old ActionBar, and I was setting the title to empty value, and using setCustomView to put my custom font TextView and center it using ActionBar.LayoutParams.

有没有更好的方式来做到这一点?使用新的工具栏作为我的动作条。

Is there a better way to do that? Using the new Toolbar as my ActionBar.

谢谢!

推荐答案

要在工具栏所有你需要做的就是记住的是,工具栏只是一个花哨的ViewGroup,因此您可以添加自定义标题,像这样:

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:

<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 。因此,在您的活动,您可以访问的标题像这样:

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:

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