How to center ImageView in a toolbar?

Spike Flail picture Spike Flail · Feb 11, 2015 · Viewed 15.4k times · Source

Been trying to center a logo inside my toolbar. When i navigate to the next activity, the "up affordance" icon is present, and it will push my logo slightly to the right. How can I keep my logo at the center of the toolbar, without removing the up affordance icon?

This is my toolbar tag

<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"

android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/primaryColor"
android:paddingTop="@dimen/app_bar_top_padding"
app:popupTheme="@style/ThemeOverlay.AppCompat.Dark"
app:theme="@style/CustomToolBarTheme">

<ImageView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_android_logo"
    android:layout_gravity="center"
    android:paddingBottom="3dp"/>
 </android.support.v7.widget.Toolbar>

Answer

Kenan Begić picture Kenan Begić · Oct 29, 2015

You can do it as following it works for me :

<androidx.appcompat.widget.Toolbar
        android:id="@+id/mainToolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="@dimen/abc_action_bar_default_height_material">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center">
            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/headerLogo"
                android:contentDescription="@string/app_name" />
            </RelativeLayout>

    </androidx.appcompat.widget.Toolbar>