onCreateOptionsMenu is never called

Solution 1:

In the latest versions of Android when using the compat library for toolbar, is very common that this happens, in order to get the menu items to display in the toolbar you must do the following:

mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);

Solution 2:

Call setHasOptionsMenu function from onCreate first. The onCreateOptionsMenu will be automatically called.

Try this:

setHasOptionsMenu(true)

Solution 3:

If the phone you test on has a menu button onCreateOptionsMenu wont't be called on start with the theme:

android:theme="@android:style/Theme.Black.NoTitleBar"

But when you click the menu button the onCreateOptionsMenu will be called. I don't know what happens on phones without hardware buttons...

Solution 4:

In the method: Fragment#onCreateView(...) you should put:

setHasOptionsMenu(true);

Then your method will be called.

Solution 5:

That is because the activity does not have the toolbar.

There are 2 steps in order to do it.

First, you need to add the toolbar in your activity.xml which is in res/layout

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"">

    <!-- add this part-->
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="?attr/actionBarTheme"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Second, let your activity append it

in JAVA

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

or in Kotlin

val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)