Reputation: 22958
I am an Android programming newbie trying to move from Activities to Fragments.
I have a simple Bluetooth app with 3 Activities:
This is a screenshot of the MainActivity, with an ellipsis menu in top-right corner:
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
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
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