1
votes

I am developing a application that should support on both phone and tablet. In this application i am using fragments from android.

Now the flow of the application is like

MainActivity --> Fragment1 --> Fragment2

In this application , i want a menu item that should show only in Fragment2 along with activity's menu items.

So i have tried one solution like adding globle menu items in MainActivity and in Fragment2 replacing the whole MainActivity's menu with Fragment2 specific Menu.

setHasOptionsMenu(true);

inside onCreateView , and implement this method.

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

Now its work exactly fine for phone layout , but when its come to tablet problem arise.

Here is my ScreenShots.

Fragment 1 enter image description here

Fragment 1 and Fragment 2 combination when pressing 9 in keybord(Tablet mode ). enter image description here

And Finally when i pressed 9 again to come back to pHone view it shows me extra menu item.

enter image description here

I just marked a extra menu item in Image. So why this me coming and how can i resolve it ?

1
i guess in tablet mode both your fragments are visible. Is that the case ??Panther
yes.bcz i need to show both fragments in tablet mode. But when i nevigate back to mobile mode , the menu item should't be thereJay Vyas
i guess this happening on a real device has a less chance. However, you should override the onConfigurationChanged and call invalidateOptionsMenu() or supportInvalidateOptionsMenu() which ever is appropiatePanther
Firstly i tried to implement onConfigurationChanged() method for different proposes in fragment. But it is not calling , don't know why :(Jay Vyas
for onConfigurationChanged not getting called you have to set android:configChanges="orientation|screenSize" in the manifest filePanther

1 Answers

0
votes

You need to hide the menu group like this in your fragment 1

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

it'll make a call to onPrepareOptionsMenu where you can hide your menu group added by fragment2

@Override
public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        menu.setGroupVisible(0, false);
}