Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide options menu on PreferenceFragment

I have an app with several fragments.

Only A fragment has an options menu. A fragment could be initiated from fragment B (which extends listfragment).

So B fragment does not have an options menu, if I select some item from it, fragment A will be initiated with an options menu and if go back, fragment B still does not have an options menu.

The problem is if I select Settings menu (which extends preferencefragment) from navigation drawer while my current window is fragment A, a settings fragment will be shown with options menu from fragment A. But if I select Settings menu from navigation drawer while my current window is fragment B, C, D (without options menu) everything works well.

Fragment A:

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

    inflater.inflate(R.menu.menu_station, menu);
}

Settings fragment:

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

    setHasOptionsMenu(true);

    sharedPreferenceSettings = new SharedPreferenceSettings(getActivity());

    addPreferencesFromResource(R.xml.settings);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_settings, container, false);
}

Where is the problem?

EDIT:

After hours of debugging I found a solution. The problem was different fragmentManager for fragments transaction. For settings fragment only I used getSupportFragmentManager(), for others - fragmentManager(). This causes some fragments from moving to back stack.

like image 423
burjulius Avatar asked Aug 05 '15 23:08

burjulius


1 Answers

I see two code suspects. Code suggestion for Fragment A:

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

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

Notes:

  • super.onCreateOptionsMenu() is normally called after inflate. This is not well documented so I am not sure what the difference is. A related SO post that many agrees as the best answer is @ Android Options Menu in Fragment.
  • setHasOptionsMenu(true) is done in the same fragment instead of Settings fragment. Fragments save its own data and states. You cannot modify states between fragments so easily.
like image 198
The Original Android Avatar answered Sep 29 '22 15:09

The Original Android