Android Add Toolbar to DialogFragment

July 24, 2018
Toolbar inflate menu, handle back button and menu click without Activity
// inflate menu
toolbar.inflateMenu(R.menu.menu_photo_pin)

// include a back icon
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black_24dp)
toolbar.setNavigationOnClickListener {
    dismiss()
}

// handle menu item click
toolbar.setOnMenuItemClickListener {
    when (it.itemId) {
        R.id.action_share_photo -> {
            // do somethong
            true
        }
        else -> {
            false
        }
    }
}

Layout

<RelativeLayout 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="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />

</RelativeLayout>

NOTE: Strangely, the DialogFragment width and height shrink to minimum when using LinearLayout, but looks fine when using RelativeLayout.

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.