Android: How to define Toolbars in XML (layout examples)

As a quick reminder to self (and an example), you can easily create a Toolbar in Android. Here’s one example that shows a Toolbar defined in some XML layout code:

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

For a little more context, here’s the full source code of that example:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

    <FrameLayout
        android:id="@+id/putPrefsContentHere"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

A Toolbar XML layout example with more options

Here’s another Android Toolbar example that shows several additional configuration options you can use:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/actionBarSize"
    app:navigationContentDescription="@string/abc_action_bar_up_description"
    android:background="?attr/colorPrimary"
    app:navigationIcon="?attr/homeAsUpIndicator"
    app:title="@string/action_settings"
    />

Note: I didn’t create these examples; they come from the Stack Overflow website.

I’ll add some more source code here over time, such as how to work with these toolbars from your Java/Android code, but until then, I hope these examples are helpful as is. (I started to use the first example in one of my projects, then realized I didn’t really need it, so I didn’t write much Java code to use it.)