Android:如何在工具栏中将标题居中 [英] Android: How to Center title in ToolBar

查看:795
本文介绍了Android:如何在工具栏中将标题居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次在项目中使用ToolBar,所以我不知道如何在android中自定义工具栏.我需要将标题居中放置在工具栏上,如何操作请告诉我.

I am using ToolBar in my project first time, so i do not know how to customized the toolbar in android. I need to centered title in to the tool bar and how to do that please tell me.

谢谢.

推荐答案

在工具栏对齐的中心简单地添加TextView的问题是在工具栏中添加了菜单项,这些菜单项将抵消居中的文本.

The problem with simply adding a TextView in the Toolbar aligned center is adding menu items in the toolbar which will offset the centered text.

要解决此问题,我将文本分层放置在工具栏的顶部,而不是内部.这样,无论您添加多少图标,都不会偏移居中的文本:

To get around this, I've layered the text on top of the Toolbar, not inside it. This way it doesn't matter how many icons you add, it will not offset the centered text:

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/ThemeOverlay.AppCompat.ActionBar">
        </android.support.v7.widget.Toolbar>

        <TextView
            android:layout_centerInParent="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/app_name"/>

    </RelativeLayout>
</android.support.design.widget.AppBarLayout>

通过这种方式,不需要任何额外的逻辑来补偿后退按钮/溢出菜单/搜索图标等在工具栏上的偏移距离,因为居中的文本位于其上方,而不位于其中.

This way there is no need for any extra logic to compensate for the offset spacing of back buttons/overflow menu/search icons etc. on the toolbar, because the centered text is above it, not in it.

这篇关于Android:如何在工具栏中将标题居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆