Does onCreateOptionsMenu pass a menu to onOptionsItemSelected? - android

Ive inflated a menu in onCreateOptionsMenu and handled functionality in onOptionsItemSelected but I was just wondering, what passes the inflated menu to onOptionsItemSelected. I'm thinking onCreateOptionsMenu but I'm not sure.

The first time a menu is needed by Android for a particular instance of an Activity, it will call onCreateOptionsMenu(). The Menu and all of its MenuItem objects that you create and return there will be remembered for as long as that activity is active, and reused for subsequent calls to onPrepareOptionsMenu() and onOptionsItemSelected(). All of these objects will go away when the activity instance is destroyed, and new ones will be created for new instances of the Activity.

try to do in onCreateOptionsMenu
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_home, menu);
}
and in onOptionsItemSelected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_search:
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
return true;
default:
return false;
}
Using item as menu

Related

how can i change the visibility of a menu item inside onOptionsItemSelected(..)

i have three menu items "enable, diable, exit". what i want to do is, when the R.id.menu_enable_bt is chosen, i want to disable it using
menu.findItem(R.id.menu_enable_bt).setVisible(false);
but i can not call
menu.findItem(R.id.menu_enable_bt).setVisible(false);
from inside the onOptionsItemSelected(..) method.
how can i change the visibility of a menu item inside onOptionsItemSelected(..)
CODE:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
Log.w(TAG, SubTag.msg("onCreateOptionsMenu"));
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
if (this.mBTAdapter.isEnabled()) {
menu.findItem(R.id.menu_enable_bt).setVisible(false);
menu.findItem(R.id.menu_disable_bt).setVisible(true);
} else {
menu.findItem(R.id.menu_enable_bt).setVisible(true);
menu.findItem(R.id.menu_disable_bt).setVisible(false);
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
Log.w(TAG, SubTag.msg("onOptionsItemSelected"));
switch (item.getItemId()) {
case R.id.menu_enable_bt:
Log.d(TAG, SubTag.bullet("onOptionsItemSelected", "menu_enable_bt"));
//menu.findItem(R.id.menu_enable_bt).setVisible(false); **how to do this**
this.mATEnableBT = new ATEnableBT();
this.mATEnableBT.execute();
break;
case R.id.menu_disable_bt:
Log.d(TAG, SubTag.bullet("onOptionsItemSelected", "menu_disable_bt"));
break;
case R.id.menu_exit:
Log.d(TAG,SubTag.bullet("onOptionsItemSelected", "menu_exit"));
finish();
break;
}
return super.onOptionsItemSelected(item);
}
you can use invalidateOptionsMenu() which will forse onCreateOptionsMenu to be called again.
From the documentation
Declare that the options menu has changed, so should be recreated. The
onCreateOptionsMenu(Menu) method will be called the next time it needs
to be displayed.
There you can check your conditions and undertake the needed actions
See the javadoc for onPrepareOptionsMenu. This is your opportunity to make changes to a menu just before it becomes visible to the user. So you should maintain some member variables describing what should be visible and use that to modify the menu items here.

How to replace menu dynamically with another in Android

I have a ListActivity (SherlockListActivity) and its content can be dynamically changed by the user. When the content changes, the options menu should be replaced.
As I learned, instead of onCreateOptionsMenu I should use onPrepareOptionsMenu that is (supposed to be) called every time the user selects the menu.
This is called right before the menu is shown, every time it is shown.
I have the following code:
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
menu.clear();
if (UserOption == UserOption1)
getSupportMenuInflater().inflate(R.menu.menu_option1, menu);
else
getSupportMenuInflater().inflate(R.menu.menu_option2, menu);
return super.onPrepareOptionsMenu(menu);
}
It is called only once during debug, so I always have the same menu.
What should I set to make it work?
Create and prepare the options menu for changing and its item selection method
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
MenuInflater inflater = getMenuInflater();
if(menuString=="red"){
inflater.inflate(R.menu.red_menu, menu);
}else if(menuString=="green"){
inflater.inflate(R.menu.green_menu, menu);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.new_game:
return true;
case R.id.help:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Like whenever you want to change menu call
String menuString="red or green";
invalidateOptionsMenu();
Like others told, if you want to have static menu use onCreateOptionsMenu, and if you want to change its visibility dynamically use onPrepareOptionsMenu along with onCreateOptionsMenu

Menu appearing on other menu android

I am developing an app using actionbar sherlock. The problem I have is that I have the menus setup and all my xml files are correct since I get no compiler and logcat error.
THe problem I am having is that when I load a fragment A with its own specific menu everything is good. But when I then move to another fragment B, fragment A menu appears on fragment B. Any ideas as to whats causing this.
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.product_allergy, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()){
case R.id.productClear:
addtoList();
break;
}
return true;
}
The menu is belonged to Activty rather than fragments. Fragment A and B are in same activity, so when A adds some items into activity's menu and then it is replaced by Fragment B, the activity does not change, i.e., the menu is still there.
If you want your Fragment B to have different menu items, override the onCreateOptionsMenu() method, remember to setHasOptionsMenu(true) in Fragment's onCreate() method.
FYI, if you simply want to clear prior fragment's menu item, call menu.clear() in onCreateOptionsMenu().
EDIT:
When you are trying to handle the action bar callback in fragments, you should do something like below:
#override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.fragmentActionBarButton:
//your code
return true;
default:
return super.onOptionsItemSelected(item);
}
}

Interaction between Activity and Fragments

In my application the main activity hosts two fragments and attached to acticity as ActionBarTabs. using the following code. NOTE: activity and the 2 fragments are defined in seperate xml layout files (See the picture at the bottom)
private void createActionTabs() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//Status Tab
String strStatus = getResources().getString(R.string.lblStatus);
ActionBar.Tab statusTab = actionBar.newTab();
statusTab.setText(strStatus);
TabListener<SFrag> sFTabListener = new TabListener<SFrag>(this, strStatus, SFrag.class);
statusTab.setTabListener(sFTabListener);
actionBar.addTab(statusTab);
//Controller Tab attached the same way
.....
}
The ActionBar Items (start and refresh) are added using
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
Now coming to my problem:
I want to update the data shown on the Status Fragment at application load, fragment resume and click of refresh menu item from the action bar. Now when I try to access the Status fragment from Main Activity using the following code
SFrag frag = (SFrag) getFragmentManager().findFragmentById(R.id.st_frag);
Log.d(TAG, "In Activity SFrag is " + (frag == null ? "null" : "not null"));
if (frag != null) {
//calls the method to update data
fragment.updateStatusData(statusInformation);
}
The getFragmentManager().findFragmentById methods always returns null. I even tried the onResume method of the activity, the fragment objects is still returned as null. So how do I access the fragment and thus accessa method of that fragment from host acticty.
Secondly, I am trying to use the action_service (its shown as Start button just for this mockup) in action bar as a toggle for satrting or stopping a background service. I can easily update the title/icon for start menu item from onOptionsItemSelected method (I save the current status running/stoppede in shared-preferences). but when I try to accees the menuItem at onStart/onResume of the activity by using
MenuItem mi = (MenuItem) findViewById (R.id.action_service);
it always returns null. So How Can I access action_service menu Item in onResume/onStart to update it.
My Application looks like this
First of all if you want to declare MenuItem, you should do it in this way :
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.main_activity, menu);
MenuItem mRefresh = menu.findItem(R.id.refresh_menu_item);
return true;
}
About updating your Fragment on applications load or Activity's start, just set selected the tab which holds your Fragment and put the code which will load the data in your Fragment on it's onStart() or onActivityCreated() method. You can override onOptionsItemSelected() in your Fragment, so you can update your views not from your Activity which holds your Fragment, but from it's own class.
Edit: Here is an example how you should handle menu from your Fragment :
public class MyFragment extends Fragment {
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true); // Do not forget this!!!
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.first_fragment, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.action_refresh:
// Do You stuff here
break;
}
return super.onOptionsItemSelected(item);
}
}
Using this you can add and use MenuItem's in your Fragment.
Hope this helps!
I can answer the MenuItem part just not the other part.
for the menu item as per the docs You can safely hold on to menu (and any items created from it), making modifications to it as desired, until the next time onCreateOptionsMenu() is called.
for example
#Override
public boolean onCreateOptionsMenu(Menu menu) {
actionMenu = menu;
return true;
}
so basically anytime you want to change one of the items you can do this
MenuItem item = actionMenu.getItem(0);

Fragment not receiving menu callbacks

I have a fragment class that extends Fragment and calls setHasOptionsMenu to participate in the menu. This class also implements onCreateOptionsMenu, onPrepareOptionsMenu and onOptionsItemSelected.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
....
}
I'm dynamically loading this fragment using a FragmentTransaction in my Activity (that extends FragmentActivity).
However none of the menu callbacks (onCreateOptionsMenu, onPrepareOptionsMenu and onOptionsItemSelected) are being called (I've debugged with some breakpoints in those methods) and the menu isn't shown.
Am I missing something? Do I need to add something in my Activity?
I'm using the Android Compatibility Library, compiling with L11 SDK and testing in a Xoom.
EDIT: I've found the problem. My AndroidManifest is targeting L11, this seems to hide the menu button and prevent from the callbacks being called. However if I remove this from the manifest I loose some other features I need (for example the activated state in lists). Does anyone know how to solve this issue (enable the menu button) without removing the targetSdkVersion=11 from the Manifest?
Aromero,
Don't forget to override the onCreateOptionsMenu using the fragment version of the method, similar to this:
#Override
public void onCreateOptionsMenu (Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.queue_options, menu);
super.onCreateOptionsMenu(menu, inflater);
}
This goes in the fragment, by the way, and adds to the inflated menu of the Activity, if there is one. Had the same problem myself, until I figured this out.
Kim
If you're having this problem with ActionBarSherlock, you need to make sure your Fragments are SherlockFragments, not mere SupportFragments, and that what you're overriding is
public void onPrepareOptionsMenu (com.actionbarsherlock.view.Menu menu) {
NOT
public void onPrepareOptionsMenu (android.view.Menu menu) {
If you do the latter, you should get some sort of warning about the function being final and you being unable to override it. This is a warning that you're trying to override the wrong function!
If you fix the error by switching the class from SherlockFragment to a mere Fragment, you can create the function . . . but it won't get called.
I had the same problem, but i think its better to summarize and introduce the last step to get it working:
Add setHasOptionsMenu(true) method in your Fragment's onCreate(Bundle savedInstanceState) method.
Override onCreateOptionsMenu(Menu menu, MenuInflater inflater) (if you want to do something different in your Fragment's menu) and onOptionsItemSelected(MenuItem item) methods in your Fragment.
Inside your onOptionsItemSelected(MenuItem item) Activity's method, make sure you return false when the menu item action would be implemented in onOptionsItemSelected(MenuItem item) Fragment's method.
An example:
Activity
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.activity_menu_item:
// Do Activity menu item stuff here
return true;
case R.id.fragment_menu_item:
// Not implemented here
return false;
default:
break;
}
return false;
}
Fragment
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
....
}
#Override
public void onCreateOptionsMenu(Menu menu) {
// Do something that differs the Activity's menu here
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.activity_menu_item:
// Not implemented here
return false;
case R.id.fragment_menu_item:
// Do Fragment menu item stuff here
return true;
default:
break;
}
return false;
}
I hope this will be helpful.
Cheers.
If you have an activity and a fragment that each loads menu items then you need to take special care of which overrides you use.
Activities can override onOptionsItemSelected and onMenuItemSelected, however fragments can only override onOptionsItemSelected.
If you override onMenuItemSelected in your activity and onOptionsItemSelected in your fragment, your fragment override will never get triggered.
Instead, use onOptionsItemSelected in both activity and fragment.
You need to make sure you call setHasOptionsMenu(true); onCreate or onCreateView is called in your fragment.
You also need to implement the override of onCreateOptionsMenu inside your fragment.
Another possible case is when you use a common id for a common action in each fragment; for instance R.id.action_add
Today I had such situation: hitting the option menu [add] was invoked the "wrong" onOptionItemSelected because each fragment (replaced dynamically using a DrawerLayout) had the same R.id.action_add.
Short story, if you have such situation always check that your fragment is visible:
if (!isVisible()) return false;
Long story, pay attention at the onOptionItemSelected chain!
MainActivity
|
| onOptionItemSelected
+-----------------------
| return false
|
MyCoolFragment1
|
| onOptionItemSelected
+-----------------------
| return false
|
MyCoolFragment2
|
| onOptionItemSelected
+-----------------------
| return true
|
[item selection handled]
If you add your fragments with (something like) this:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, MyCoolFragment1.newInstance())
.commit()
and you have defined the same id for a common action (let's say R.id.action_add) in each fragment;
don't forget to add this line to each: if (!isVisible()) return false;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (!isVisible()) return false; // <-- Not visible? skip!
if (item.getItemId() == R.id.action_add) {
//.TODO whatever
return true; //.Handled!
}
return false; //.Skip
}
I had this problem when I was using the ViewPagerIndicator in conjunction with ActionBarSherlock. Although it appeared this was fixed I still ran into the problem. The work around I found was to call into the fragment manually.
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
Toast.makeText(this, "From activity", Toast.LENGTH_SHORT).show(); // TODO
Fragment currentFragment = mAdapter.getItem(mPager.getCurrentItem());
if (currentFragment != null && currentFragment instanceof SherlockFragment)
{
((SherlockFragment)currentFragment).onOptionsItemSelected(item);
}
return super.onOptionsItemSelected(item);
}
I've found the problem. The AndroidManifest is targeting SDK 11, this seems to hide the menu button and prevent from the callbacks being called. I assume that this breaks the compatibility of the menu button that seems to be replaced by the action bar in Android 3.0
I think you have implemented onCreateOptionsMenu, onPrepareOptionsMenu and onOptionsItemSelected in the class that extends Fragment. Try by doing that in your Activity class where you are loading this fragment
From the android developer site - link
Note: If you inflate menu items from a fragment, via the Fragment
class's onCreateOptionsMenu() callback, the system calls
onOptionsItemSelected() for that fragment when the user selects one of
those items. However, the activity gets a chance to handle the event
first, so the system first calls onOptionsItemSelected() on the
activity, before calling the same callback for the fragment. To ensure
that any fragments in the activity also have a chance to handle the
callback, always pass the call to the superclass as the default
behavior instead of returning false when you do not handle the item.
Therefore Marco HC is the best answer of all.
If your toolbar is defined in the parent activity xml, make sure you do this in your fragment
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
....
Toolbar toolbar = (Toolbar)getActivity().findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
setHasOptionsMenu(true);
}
And then of course, override onCreateOptionsMenu like below
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.edit_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
This is the only solution that worked for me!
I had same problem and solution that worked for me is:
Remove or comment any onOptionsItemSelected() ,onMenuItemSelected() even onPrepareOptionMenu() and leave in Activity onCreateOptionsMenu() only:
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.layout.menu, menu);
return true;
}
In Fragment class, in onCreateView(), put:
setHasOptionsMenu(true);
In Fragment class add :
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu,inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.action_insert:
//doing stuff
return true;
}
return false;
}
Tested and worked on Android 4.4

Categories

Resources