• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Help putting Menu into a Toolbar in Activity

SlowHand63

Lurker
I am writing because I cannot successfully add a Menu into a Toolbar. i have made a toolbar using the Toolbar element. I have tried using the other flavors of a toolbar (androidx for instance) and all of them crash my app. So I am using the android-recommend 'Toolbar' - it's the only one that flies.

Anyway, I can see the Toolbar! Now for the Menu I wish to add. I have overridden the method

@override
public boolean onPrepareOptionsMenu (Menu menu) {
super.onPrepareOptionsMenu( menu );
getMenuInflater().inflate( R.menu.home_mainmenu, menu );
invalidateOptionsMenu();
return false;
}

I have tried endless variations and always no joy. So would some kind angel out there please give an example of how to place a Menu into a Toolbar?

Someone suggested altering the 'AppTheme' in styles.xml to: Theme......NoActionBar. I tried it both ways with no effect.

I'm a very experienced programmer but am new to Android, so all of these different versions of the same thing really confuse me..... Looking forward to hearing from you!

TIA

So - I figured it out. May this be of use to you.

First, we are talking about the xml entity <Toolbar>. Nothing more, Nothing less.

Your Activity class must extend Activity. --- NOT AppCompatActivity

In your Activity.onCreate(...) put this:

// the ui toolbar already exists, so a temporary variable works fine
Toolbar toolbar = findViewById(R.id.mytoolbar); // substitute your id
setActionBar( toolbar );

Now you must override like so:
/*
default processing to be done only once
boolean bMenuInitialized should be declared as a class field to false
*/
@override
public boolean onPrepareOptionsMenu (Menu menu) {
super.onPrepareOptionsMenu( menu );
if ( !bMenuInitialized ) {
getMenuInflater().inflate( R.menu.home_mainmenu, menu );
bMenuInitialized = true;
}
return true;
}

This override gets called every time the menu is displayed. That's why you only want to call it once i this context, so trip your flag - in this case bMenuInitialized. Good luck!
 
Last edited:
Back
Top Bottom