Android:如何在ToolBar中居中标题

Ume*_*wat 17 android toolbar

我第一次在我的项目中使用ToolBar,所以我不知道如何在android中自定义工具栏.我需要将标题集中到工具栏中,如何做到这一点请告诉我.

预先感谢.

Lit*_*ild 32

请记住,Toolbar这ViewGroup就像其他人一样.所以你可以填充View它.在你的情况下,你需要一个TextView内部Toolbar.

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

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Some Fancy Title"
        android:gravity = "center"
        android:id="@+id/toolbar_title" />

</android.support.v7.widget.Toolbar>
Run Code Online (Sandbox Code Playgroud)

现在,Toolbar首先检索它然后使用,将其设置为操作栏setSupportActionBar().

由于的重力TextView设定为center,文本必须居中.

  • 在我的例子中,我将工具栏设置为操作栏.我左边有一个导航图标.通过这种方式,工具栏的标题不再居中.它偏向正确的一点点.怎么解决? (14认同)
  • @ Eggman87尝试将textview的WIDTH设置为WRAP_CONTENT并将其LAYOUT_GRAVITY设置为CENTER.这样,即使显示主页按钮,textview也会将其自身置于父级内部. (6认同)
  • 您应该使用layout_gravity而不是gravity.gravity定义视图中的内容如何放置在其中,而layout_gravity指示视图应如何相对于其父视图放置. (5认同)
  • 你还应该为`Toolbar`设置`gravity`和`layout_gravity`. (2认同)

jes*_*nte 32

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

为了解决这个问题,我将文本分层放在工具栏的顶部,而不是在其中.这样,添加多少图标并不重要,它不会偏移居中文本:

<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>
Run Code Online (Sandbox Code Playgroud)

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


tom*_*dre 10

您可以通过包装标题和级别右侧填充来强制工具栏到中心,其中默认左侧填充标题.然后将背景颜色添加到工具栏的父级,这样通过包装标题剪切的部分是相同的颜色(在我的示例中为白色):

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

            <android.support.v7.widget.Toolbar
               android:id="@+id/toolbar"
               android:layout_width="wrap_content"
               android:layout_height="56dp"
               android:layout_gravity="center_horizontal"
               android:paddingEnd="15dp"
               android:paddingRight="15dp"
               android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
               app:titleTextColor="@color/black"/>

</android.support.design.widget.AppBarLayout>
Run Code Online (Sandbox Code Playgroud)


Ume*_*wat 9

ToolBar是一个View Group.所以中心对齐文本使用

app_bar.xml

<?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/in.chabu"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    app:theme="@style/ToolBarTheme" 
    android:minHeight="?attr/actionBarSize">

     <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/title_activity_sign_up"
        android:layout_gravity="center"
        android:id="@+id/toolbar_title" 
        android:textStyle="bold"
        android:textColor="@android:color/white"/>

</android.support.v7.widget.Toolbar>
Run Code Online (Sandbox Code Playgroud)

activity_sign_up

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="in.chabu.activities.SignUpActivity" >

    <include 
        android:id="@+id/tool_bar"
        layout="@layout/app_bar"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tool_bar"
        android:text="@string/hello_world" />

</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

活性起着

public class SignUpActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up);

        Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);

        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayShowTitleEnabled(false);
    }


}
Run Code Online (Sandbox Code Playgroud)


Har*_*ung 8

当你有一个Home或Up按钮以及居中的标题,并且标题不再居中并稍微向右移动一点时,将textview设置为width = wrap_content和layout_gravity = center

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"/>
Run Code Online (Sandbox Code Playgroud)


use*_*020 8

只是将另一个TextView放入内部Toolbar并不足以使标题相对于屏幕居中,其位置将取决于工具栏中的其他项目(后退按钮,菜单项).

要使标题居中,您可以手动设置其位置:

扩展android.support.v7.widget.Toolbar类并进行以下更改:

  1. 加 TextView
  2. 覆盖onLayout()并设置TextView位置以使其居中(titleView.setX((getWidth() - titleView.getWidth())/2))
  3. 覆盖setTitle()将标题文本设置为新文本视图的位置
    public class CenteredToolbar extends Toolbar {

        private TextView titleView;

        public CenteredToolbar(Context context) {
            this(context, null);
        }

        public CenteredToolbar(Context context, @Nullable AttributeSet attrs) {
            this(context, attrs, android.support.v7.appcompat.R.attr.toolbarStyle);
        }

        public CenteredToolbar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);

            titleView = new TextView(getContext());

            int textAppearanceStyleResId;
            TypedArray a = context.getTheme().obtainStyledAttributes(attrs,
                    new int[] { android.support.v7.appcompat.R.attr.titleTextAppearance }, defStyleAttr, 0);
            try {
                textAppearanceStyleResId = a.getResourceId(0, 0);
            } finally {
                a.recycle();
            }
            if (textAppearanceStyleResId > 0) {
                titleView.setTextAppearance(context, textAppearanceStyleResId);
            }

            addView(titleView, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        }

        @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b) {
            super.onLayout(changed, l, t, r, b);
            titleView.setX((getWidth() - titleView.getWidth())/2);
        }

        @Override
        public void setTitle(CharSequence title) {
            titleView.setText(title);
        }
    }

在布局中,您可以像这样使用此类:

<com.example.CenteredToolbar 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="?attr/colorPrimary"
    android:elevation="4dp"
    android:theme="@style/ToolbarTheme"/>
Run Code Online (Sandbox Code Playgroud)

此外,要使新标题文本看起来像标准标题,您应该将titleTextAppearance样式应用于new TextView(titleView.setTextAppearance(context, textAppearanceStyleResId)).


Liu*_*NO. 8

最终用户界面如下所示: 在此输入图像描述 对于我的项目,我左侧有导航图标,右侧有菜单(超过1个),想要将标题置于中心位置.

我有setSupportActionBar(toolbar),和_actionBar.setCustomView(R.layout.actionbar_filter);.我的布局文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/lib_action_bar_filter_view_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="?attr/selectableItemBackgroundBorderless"
                android:gravity="center">

    <TextView
        android:id="@id/lib_action_bar_filter_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:maxLines="2"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:textColor="@android:color/white"
        android:textSize="15sp"/>

</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

我的工具栏扩展了android.support.v7.widget.Toolbar,然后(一种硬代码)测量RelativeLayout的大小,最后将它布置在horizental中心.

/**
 * Customized the <code>RelativeLayout</code> inside the <code>Toolbar</code>.
 * Because by default the custom view in the <code>Toolbar</code> cannot set
 * width as our expect value. So this class allows setting the width of the
 * <code>RelativeLayout</code> to take up any percentage of the screen width.
 */
public class CenteredToolbar extends Toolbar {

private static final double WIDTH_PERCENTAGE = 0.8;

private TextView titleView;

public CenteredToolbar(Context context) {
    this(context, null);
}

public CenteredToolbar(Context context, @Nullable AttributeSet attrs) {
    this(context, attrs, android.support.v7.appcompat.R.attr.toolbarStyle);
}

public CenteredToolbar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int childCount = getChildCount();
    for (int i = 0; i < childCount; i++) {
        View view = this.getChildAt(i);
        if (view instanceof RelativeLayout) {
            int width = getMeasuredWidth();
            ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
            layoutParams.width = (int) (width * WIDTH_PERCENTAGE);
            view.setLayoutParams(layoutParams);
            break;
        }
    }
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    super.onLayout(changed, l, t, r, b);
    int childCount = getChildCount();
    for (int i = 0; i < childCount; i++) {
        View view = this.getChildAt(i);
        if (view instanceof RelativeLayout) {
            forceTitleCenter(view);
            break;
        }
    }
}

/**
 * Centering the layout.
 *
 * @param view The view to be centered
 */
private void forceTitleCenter(View view) {
    int toolbarWidth = getMeasuredWidth();
    int relativeLayoutWidth = view.getMeasuredWidth();
    int newLeft = (int) (toolbarWidth - relativeLayoutWidth) / 2;
    int top = view.getTop();
    int newRight = newLeft + relativeLayoutWidth;
    int bottom = view.getBottom();
    view.layout(newLeft, top, newRight, bottom);
}
}
Run Code Online (Sandbox Code Playgroud)

附上我的工具栏布局.也许你不需要这个,我只是粘贴在这里供某人参考:

<?xml version="1.0" encoding="utf-8"?>
<com.chinalwb.CenteredToolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/vmosolib_toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:elevation="4dp"
    app:contentInsetEnd="0dp"
/>
Run Code Online (Sandbox Code Playgroud)


小智 5

可以使用MaterialToolbar,安卓支持material:1.4.0-alpha02

https://github.com/material-components/material-components-android/commit/cbf528e3a6deaa2bc39d0836b3a850b27c2ada49。

    implementation 'com.google.android.material:material:1.4.0-alpha02'
Run Code Online (Sandbox Code Playgroud)
<com.google.android.material.appbar.MaterialToolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:titleCentered="true" />
Run Code Online (Sandbox Code Playgroud)


Jay*_*mar 1

我完全不明白你的问题..但我找到了这样的解决方案

要在工具栏中使用自定义标题,您需要做的就是记住工具栏只是一个奇特的 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>
Run Code Online (Sandbox Code Playgroud)

这意味着您可以根据需要设置 TextView 的样式,因为它只是一个常规的 TextView。因此,在您的活动中,您可以像这样访问标题:

Toolbar toolbarTop = (Toolbar) findViewById(R.id.toolbar_top);
TextView mTitle = (TextView) toolbarTop.findViewById(R.id.toolbar_title);
Run Code Online (Sandbox Code Playgroud)