My application has three tabs, and I use a pager to switch between tabs. Each tab has its own fragment. I added the Action and Action buttons to the action panel of the main action using the OptionsMenu methods. Now I want to add a new action button to the action bar, but only for the first tab and the first fragment, and I do not want it to appear on other fragments when they are displayed on the tabs.
I have this layout for the main menu, which was created in the main action -
<item android:id="@+id/action_settings" android:title="@string/action_settings" android:orderInCategory="100" app:showAsAction="never" /> <item android:id="@+id/help" android:title="@string/help" android:orderInCategory="100" app:showAsAction="never" /> </menu>
This menu displays correctly and works as expected.
I have another menu, menu_prelaunch_fragment for the first fragment -
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/clear_form" android:title="Clear" android:icon="@drawable/ic_action_action_delete" app:showAsAction="always" /> </menu>
and I add it to the action bar using the following code in the first fragment -
@Override public void onCreate(Bundle savedInstance) { Log.d(TAG, "onCreate"); super.onCreate(savedInstance); setHasOptionsMenu(true); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflator) { Log.d(TAG, "onCreateOptionsMenu"); inflator.inflate(R.menu.menu_prelaunch_fragment, menu); super.onCreateOptionsMenu(menu, inflator); } @Override public boolean onOptionsItemSelected(MenuItem item) { Log.d(TAG, "onOptionsItemSelected"); if (item.getItemId() == R.id.clear_form) clearFragmentData(); return super.onOptionsItemSelected(item); }
The problem is that this added button does not disappear when I go to other fragments on other pages / tabs. The remaining fragments do not have an option menu code in them.
Then I added this code to other fragments to remove one button.
@Override public void onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate"); super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onPrepareOptionsMenu (Menu menu) { menu.findItem(R.id.clear_form).setVisible(false); super.onPrepareOptionsMenu(menu); }
But now the cleanup button does not appear on the action bar no matter which tabs are selected.
How to add an action button to the action bar for only one tab (i.e. a fragment) in my three tab (i.e. about three fragments)? It should appear only when this tab (fragment) is selected (displayed).
Thanks!