Fragment Option Menu Avoid Showing One Fragment Menu In another
Asked Answered
W

3

6

I am Replacing 2 Fragments One After another, and both fragments have different option menus. When I replace 2nd fragment it is showing menus of 1st fragment also. setHasOptionMenu(true); has set in both fragments.

I want to show only that option menu I am creating in particular fragment and Want to Avoid options of other fragments.

please help, Thanks

Wayne answered 8/3, 2016 at 9:9 Comment(4)
Can you post some code as to how you are replacing the fragments? Are you unsing FragmentTransaction .replace()? How is your xml setup/how do you initialize the fragments?Correspond
Best way is to have all the menus in one single file and inflate in activity. After loading Fragment from Activity call invalidateOptionsMenu() and then in onPrepareOptionsMenu() handle the visibility of respective menu items.Willenewillet
@Jogendra Gouda, have you tried my solution ?Magdalenemagdalenian
Not possible AFAIK, you will have to name it differently though can keep value/title same.Dramamine
M
0

Just call invalidateOptionsMenu() on onCreate().

More reference check this one.

Hope this will help you.

Magdalenemagdalenian answered 15/3, 2016 at 11:4 Comment(0)
M
0

This is how your activity will be

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            //your menu item 
                return true;
        }

        return super.onOptionsItemSelected(item); // important line
    }

In your fragment onCreateView() method

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        setHasOptionsMenu(true); //imp line
        return inflater.inflate(R.layout.fragment_following, container, false);
    }



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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    switch (id) {
        case R.id.action_1:
            // do stuff
            return true;

        case R.id.action_2:
            // do more stuff
            return true;
    }

    return false;
}
Mcclanahan answered 15/3, 2016 at 11:7 Comment(0)
A
0

Just after replacing the fragment(or commiting the fragment transaction), you have to declare that option menu has changed, you can do so by calling invalidateOptionsMenu(). The onCreateOptionsMenu(Menu) method will be called the next time it needs to be displayed.

NOTE: you would need to call supportInvalidOptionsMenu in case if you are using AppCompat support library.

Aspergillum answered 22/3, 2016 at 4:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.