onCreateOptionsMenu not called when starting new activity

Errol Green picture Errol Green · Apr 24, 2015 · Viewed 17.4k times · Source

My onCreateOptionsMenu works only in my MainActivity and when I try to put another onCreateOptionsMenu in another activity to inflate a different menu it does not display my menu bar (note that I have it setup exactly the same in both activities).

I do not get any errors, it just does not display my menu bar on my secondary activity.

Here is my code:

@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.expanded_view_layout);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    //noinspection SimplifiableIfStatement
    int id = item.getItemId();
    if (id == R.id.action_back) {
        finish();
    }
    return super.onOptionsItemSelected(item);
}

Also note that I changed getMenuInflater() to super.getMenuInflater() and got same result.

Answer

Mr.Q picture Mr.Q · May 26, 2017

In case you are using tool bar in your activity

@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_map);
   mToolbar = (Toolbar) findViewById(R.id.tool_bar);
   setSupportActionBar(mToolbar);
}