Alexander Farber
Alexander Farber

Reputation: 22958

Moving from Activities to Fragments: how to display the menu just for 1 Fragment?

I am an Android programming newbie trying to move from Activities to Fragments.

I have a simple Bluetooth app with 3 Activities:

  1. MainActivity (with "Settings" in menu)
  2. SettingsActivity with few checkboxes and seekbars
  3. ScanningActivity showing Bluetooth devices in a list

This is a screenshot of the MainActivity, with an ellipsis menu in top-right corner:

main

I am trying to change my app to have a single MainActivity, which displays one of 3 Fragments (MainFragment, SettingsFragment or ScanningFragment):

public class MainActivity extends Activity implements 
                        MainListener, /* my 3 custom interfaces */
                        SettingsListener, 
                        ScanningListener, 
                        BleWrapperUiCallbacks {

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main); // empty FrameLayout

    Fragment fragment = new MainFragment();
    getFragmentManager().beginTransaction()
        .replace(R.id.root, fragment, "main")
        .commit();
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_settings:
            Fragment fragment = new SettingsFragment();
            getFragmentManager().beginTransaction()
                .addToBackStack(null)
                .replace(R.id.root, fragment, "settings")
                .commit();
            break;
    }

    return super.onOptionsItemSelected(item);
}

My problem is that currently the "Settings" menu is always displayed - while I only need to display it when the MainFragment is shown (but not when SettingsFragment or ScanningFragment are shown).

How to solve this best?

And do I have to introduce an enum variable, which I can query to find which of the 3 Fragments is currently displayed or is there a nicer way?

Upvotes: 0

Views: 386

Answers (2)

vinitius
vinitius

Reputation: 3274

Use the onCreateOptionsMenu() in the fragment you wish to show the menu, not in your activity. In the others fragments you don't want to display the menu, use setHasOptionMenu(false).

To get your current fragment, use the findFragmentByTag() from your FragmentManager

Upvotes: 1

Shooky
Shooky

Reputation: 1299

You can Override onCreateOptions menu in the fragment that should have the menu and only inflate it there.

In the fragment:

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

Upvotes: 1

Related Questions