Use the android.support.v7.widget.Toolbar
and just do:
toolbar.inflateMenu(R.menu.my_menu)
toolbar.setOnMenuItemClickListener {
onOptionsItemSelected(it)
}
Most of the suggested solutions like setHasOptionsMenu(true)
are only working when the parent Activity has the Toolbar in its layout and declares it via setSupportActionBar()
. Then the Fragments can participate in the menu population of this exact ActionBar:
Fragment.onCreateOptionsMenu(): Initialize the contents of the Fragment host's standard options menu.
If you want a standalone toolbar and menu for one specific Fragment you can to do the following:
menu_custom_fragment.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_save"
android:title="SAVE" />
</menu>
custom_fragment.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
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="wrap_content" />
...
CustomFragment.kt
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(layout.custom_fragment, container, false)
val toolbar = view.findViewById<Toolbar>(R.id.toolbar)
toolbar.inflateMenu(R.menu.menu_custom_fragment)
toolbar.setOnMenuItemClickListener {
onOptionsItemSelected(it)
}
return view
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.menu_save -> {
// TODO: User clicked the save button
true
}
else -> super.onOptionsItemSelected(item)
}
}
Yes, it's that easy. You don't even need to override onCreate()
or onCreateOptionsMenu()
.
PS: This is only working with android.support.v4.app.Fragment
and android.support.v7.widget.Toolbar
(also be sure to use AppCompatActivity
and an AppCompat
theme in your styles.xml
).