Mobile development

Alex Zhukovich

How to set an image to Toolbar in Android app


Today I would like to talk how to set an image to a toolbar. It can help you with the branding of your application.

Firstly need to create a project. In this short tutorial, I created an application from the template “Blank Activity” from “File/New Project…” menu item.
Screen Shot 2016-02-17 at 23.37.16

After it need to update layout activity_main.xml. The main idea find place when you use Toolbar

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    app:popupTheme="@style/AppTheme.PopupOverlay" />    

and change it to:

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    app:popupTheme="@style/AppTheme.PopupOverlay" >

    <ImageView
        android:src="@drawable/header_image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</android.support.v7.widget.Toolbar>  

In this example for toolbar I used the next image:
header_image

As a result, you can see the following picture:
device_screen

Tap on the ImageView

If you want to handle tap on the ImageView from the Toolbar, we should be sure that out ImageView has an ID. Afterwards, we can find View by ID and use the setOnClick method for handling it.

toolbarHeader.setOnClickListener {
    Toast.makeText(this, "toolbarHeader#click", Toast.LENGTH_SHORT).show()
}

I hope it was helpful to you.
Have a nice day.

« »

© 2018 Mobile development. Theme by Anders Norén.