How to center ImageView in a toolbar?

You need to use the AppBarLayout widget with the Toolbar widget and setting the contentInsetStart to 0dp. Otherwise the Toolbar will about 8dp of padding at the start (to insert the navigation buttons if needed)

Here's the working code:

<android.support.design.widget.AppBarLayout
    android:id="@+id/appBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:fitsSystemWindows="false"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:contentInsetStart="0dp"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="left"
            android:adjustViewBounds="true"
            android:scaleType="centerInside"
            android:src="@drawable/company_logo" />

    </android.support.v7.widget.Toolbar>


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

Also, make sure you use ?attr/actionBarSize as the height for the toolbar as this is the default actionBar height and will adjust to all the different screen sizes.


In javadoc, it says:

One or more custom views. The application may add arbitrary child views to the Toolbar. They will appear at this position within the layout. If a child view's Toolbar.LayoutParams indicates a Gravity value of CENTER_HORIZONTAL the view will attempt to center within the available space remaining in the Toolbar after all other elements have been measured.

It means you cannot do it unless you create a custom toolbar or remove the icon.


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>