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

新手上路,请多包涵

我这样做:

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

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

原文由 anupam x 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 407
2 个回答

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

旧帖

要在工具栏中使用自定义标题,您需要做的就是记住工具栏只是一个花哨的 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);

原文由 gmetax 发布,翻译遵循 CC BY-SA 4.0 许可协议

textview android.support.v7.appcompat 24.2 Toolbar setTitleTextAppearance

在 styles.xml 中创建新样式

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

并使用它

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

原文由 Rainmaker 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题