Change the status of the action bar menu depending on the fragment

I am trying to show / hide elements in my action bar depending on which fragment is visible.

In my MainActivity, I have the following

/* Called whenever invalidateOptionsMenu() is called */ @Override public boolean onPrepareOptionsMenu(Menu menu) { if(this.myFragment.isVisible()){ menu.findItem(R.id.action_read).setVisible(true); }else{ menu.findItem(R.id.action_read).setVisible(false); } return super.onPrepareOptionsMenu(menu); } 

This works great, however, when the device is rotated, a problem occurs. After the rotation is completed, onPrepareOptionsMenu is called again, however this time this.myFragment.isVisible () returns false ... and therefore the menu item is hidden when it is clear that the fragment is visible (as shown in the image on the screen).

+6
source share
3 answers

Edit: this is a quick and dirty fix, see es0329 answer below for a better solution.

Try adding this attribute to your activity tag in your Android manifest:

 android:configChanges="orientation|screenSize" 
-3
source

Based on the fragment APIs , we can add elements to the action bar based on each fragment with the following steps: Create res/menu/fooFragmentMenu.xml , which contains menu items, as usual for the standard menu.

 <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/newAction" android:orderInCategory="1" android:showAsAction="always" android:title="@string/newActionTitle" android:icon="@drawable/newActionIcon"/> </menu> 

At the top of the FooFragment onCreate method, indicate that it has its own menu items that you want to add.

 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); ... } 

Override onCreateOptionsMenu where you inflate the snippet menu and attach it to your standard menu.

 @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.fooFragmentMenu, menu); super.onCreateOptionsMenu(menu, inflater); } 

Override onOptionItemSelected in your fragment, which is called only when the same host method Activity / FragmentActivity sees that it has no case to choose from.

 @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.newAction: ... break; } return super.onOptionsItemSelected(item); } 
+24
source

Try using the fragment setRetainInstance(true); when your fragment is attached to Activity. Thus, your fragment will save the current values ​​and will cause a life cycle when the device rotates.

0
source

Source: https://habr.com/ru/post/951685/


All Articles