Search code examples
androidandroid-layoutandroid-5.0-lollipopandroid-toolbar

Where to define XML for the Toolbar widget in Android 5.0?


Okay, I've been going through several StackOverflow posts now, but I'm still confused as to where this xml for my Toolbar goes.

<android.support.v7.widget.Toolbar
android:id=”@+id/my_awesome_toolbar”
android:layout_height=”wrap_content”
android:layout_width=”match_parent”
android:background=”@styles/colorPrimary” />

Does it go in my /layout/activity_main.xml?


Solution

  • Toolbar is a generalization of Action bars for use within app layouts, now to answer your question there are two practices:

    Bad practice:

    Bad practice is to define the Toolbar in every layouts.

    Standard practice:

    Standard practice is to define a layout and reference it in a base activity. You just need to include this Toolbar layout in whichever layout you want (by using <include>) and extend the defined base activity in whichever activity.

    This standard practice will help you keeping a single code base for Toolbar and save your time from defining Toolbar every time.

    Example: Google I/O 2014 android app

    toolbar_actionbar_with_headerbar.xml

    <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:iosched="http://schemas.android.com/apk/res-auto"
        style="@style/HeaderBar"
        iosched:theme="@style/ActionBarThemeOverlay"
        iosched:popupTheme="@style/ActionBarPopupThemeOverlay"
        android:id="@+id/toolbar_actionbar"
        iosched:titleTextAppearance="@style/ActionBar.TitleText"
        iosched:contentInsetStart="?actionBarInsetStart"
        android:layout_width="match_parent"
        android:layout_height="?actionBarSize" />
    

    This toolbar layout is referenced in settings activity as given below:

    activity_settings.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".ui.SettingsActivity">
    
        <include layout="@layout/toolbar_actionbar_with_headerbar" />
    
        <FrameLayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />
    </LinearLayout>