Search code examples
androidmaterial-designandroid-toolbarandroid-constraintlayout

Android Custom Toolbar centering with back/menu buttons


I thought this would be a simple task but oh Android, why is this so hard :facepalm:

I have this custom Toolbar layout

<android.support.v7.widget.Toolbar
    ....width/height stuff>
    <ConstraintLayout
      ....width/height stuff>
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:orientation="vertical"
            android:gravity="center"
            ...start_toStartOf="parent"
            ...end_toEndOf="parent"
            ...top_toTopOf="parent"
            ...bottom_toBottomOf="parent">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Hello World!"/>
        </LinearLayout>
    </ContstraintLayout>
</android.support.v7.widget.Toolbar>

This works fine if I don't put HomeAsUpButton or a menu item(s).

This screenshot shows how it's not centered when I put a back button enter image description here

This back button is not part of my Toolbar layout because I want my toolbar implementation to be as 'raw' as possible.

Back button is added by

actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);

and it pushes my layout to right.

Q: Is there any way I can ignore left button or menu buttons that will be added to the right, and center the TextView? Do I really have to hack it and make my own Left Button/menu-like layout?

If my question is unclear, please let me know and I'll elaborate.

Thank you in advance.


Solution

  • Try replacing your Toolbar XML code with this:

     <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?android:attr/actionBarSize"
            android:background="@android:color/transparent"
            android:elevation="1dp"
            app:layout_collapseMode="pin"
            app:theme="@style/toolbarTheme">
    
            <TextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:maxLines="1"
                android:textColor="@color/textPrimary"
                android:textSize="@dimen/font_toolbar"
                tool:text="Title" />
        </android.support.v7.widget.Toolbar>
    

    Also set properties:

    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setDisplayShowTitleEnabled(false);