简体   繁体   中英

Why won't my toolbar title center?

I'm wondering why my toolbar title doesn't center when I add a home icon on the far left. If I remove this icon, it is perfectly centered. However, if there is an icon in the toolbar then the title always shifts slightly to the right.

I add the icon to the toolbar programmatically using

 getSupportActionBar().setDisplayShowHomeEnabled(true);
 getSupportActionBar().setDisplayHomeAsUpEnabled(true);
 getSupportActionBar().setHomeButtonEnabled(true);

And my toolbar with TextView (title) is here:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">


<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tool_bar_test"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:background="#FF86B39A"
    android:fitsSystemWindows="true"
    app:contentInsetLeft="5dp"
    app:contentInsetStart="5dp">

        <TextView
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="Test"
            android:textColor="#ffffff"
            android:textSize="25sp"
            android:textStyle="bold" />
    </android.support.v7.widget.Toolbar>
    ...

Why could this be happening? It seems like the TextView shifts to the right from the center by the icon's width. Overall in the toolbar my aim is to have an icon on the left and title exactly in the center.

Grateful for any help

Use gravity center

 <android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:layout_alignParentTop="true"
    android:background="@color/primaryColor"
    app:layout_scrollFlags="scroll|enterAlways"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
>
    <TextView
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="itleT"
        android:textColor="@color/white"
        android:textSize="25sp"
        android:textStyle="bold"/>
</android.support.v7.widget.Toolbar>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM