I recently started updating my application to use the new toolbar component introduced on Android 5.0, in favor of using a custom view over the action bar. I followed the explorer here: http://antonioleiva.com/material-design-everywhere/ and adding a toolbar is fine. The problem is that I am using a navigation structure in which I have MainActivity and replacing the content by adding snippets to the backstack. I override the onCreateOptionsMenu and onOptionsItemSelected methods in my snippets to set the menu items in the Toolbar, and the icons change accordingly when I switch Snippets, and onOptionsItemSelected is called in the first snippet, but not called when I add the snippet to the backstack. The onOptionsItemSelected function in MainActivity is not even called, so the event is not consumed by Activity. I also tried just replacing the Fragment without adding it to the backstack, but onOptionsItemSelected is still not being called. What am I missing to get onOptionsItemSelected to call after I change the contents of the fragment? The corresponding code is posted below.
Application Theme:
<style name="AppThemeLight" parent="@style/Theme.AppCompat.Light"> <item name="actionMenuTextColor">@color/white</item> <item name="android:windowDisablePreview">true</item> <item name="android:windowNoTitle">true</item> <item name="android:windowActionBarOverlay">true</item> <item name="android:windowActionBar">false</item> </style>
Adding a toolbar to MainActivity:
Toolbar toolbar = (Toolbar)findViewById( R.id.toolbar ); if (toolbar != null) { setSupportActionBar( toolbar ); getSupportActionBar().setDisplayHomeAsUpEnabled( true ); toolbar.setNavigationIcon( R.drawable.toolbar_icon_menu ); }
Menu Functions in MainActivity:
@Override public boolean onCreateOptionsMenu( Menu menu ) { Log.v( "Main", "onCreateOptionsMenu" ); return super.onCreateOptionsMenu( menu ); } @Override public boolean onOptionsItemSelected( MenuItem item ) { Log.v( "Main", "onOptionsItemSelected" ); return super.onOptionsItemSelected( item ); }
Functions of the top-level fragment:
@Override public void onCreateOptionsMenu( Menu menu, MenuInflater inflater ) { super.onCreateOptionsMenu( menu, inflater ); inflater.inflate( R.menu.main_looks, menu ); } @Override public boolean onOptionsItemSelected( MenuItem item ) { switch (item.getItemId()) { case R.id.miOptions: onOptions(); return true; default: return super.onOptionsItemSelected( item ); } }
Menu functions in a fragment by stack
@Override public void onCreateOptionsMenu( Menu menu, MenuInflater inflater ) { super.onCreateOptionsMenu( menu, inflater ); inflater.inflate( R.menu.user, menu ); } @Override public boolean onOptionsItemSelected( MenuItem item ) { Log.v( "User", "onOptionsItemSelected" ); switch (item.getItemId()) { case R.id.miUserShare: onShareUser(); return true; case R.id.miUserEdit: onEditUserProfile(); return true; default: return super.onOptionsItemSelected( item ); } }