I'm practising adding menu items and trying to react to menu item clicks. According to the developer's guide, it says:
Tip: Android 3.0 adds the ability for you to define the on-click behavior for a menu item in XML, using the android:onClick attribute. The value for the attribute must be the name of a method defined by the activity using the menu. The method must be public and accept a single MenuItem parameter—when the system calls this method, it passes the menu item selected. For more information and an example, see the Menu Resource document.
However, the sample code in the same page doesn't follow the rule: the methods do not pass the MenuItem parameter. The sample code is:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.new_game:
newGame();
return true;
case R.id.help:
showHelp();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
My question is: Shouldn't method calls be newGame(MenuItem item) and showHelp(MenuItem item), instead of newGame() and showHelp()? When I tested my own, (MenuItem item) argument was needed in fact, otherwise, the app was crashing, even though it compiles correctly.
Any help would be appreciated.
onOptionsItemSelected is the alternative to defining onClick attributes and what is available prior to Android 3.0 (important if you want to be backward compatible). It is simply a different way of providing the same process flow. Of course, onClick has the potential to crash your application on runtime, rather than onOptionsItemSelected not handling a menu item (simply causing it to do nothing).
Related
I was reading the help section on google's android page on OptionsMenus and ActionsBars:
http://developer.android.com/guide/topics/ui/actionbar.html
And they included a note that stated that when using fragments, the activity's onOptionsItemSelected method would be called beforethe fragment's is called, their by making it necessary to include the default: return super.onOptionsItemSelected at the end of the onOptionsItemSelected method definition. They included the following method example but did not state if this was meant to be an example within an Activity definition or a Fragment definition. I was a little confused on this and wanted to ask for clearification. based on the use of "super" it would suggest it's inside the fragment getting passed up to the Activity, but this disagrees with their statement that the Activity gets called first. If it's meant to be an example in the Activity and "super" refers to the parent Application class, then I am not clear on how it gets referred back to the Fragment. Any notes of clearification would be appreciated.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_search:
openSearch();
return true;
case R.id.action_compose:
composeMessage();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Your MyActivity extends Activity and thus inherits its methods, one of which is onOptionsItemSelected() that you are overriding.
Calling super.whatever() says: I want to override this method whatever()from the superclass Activity, but still run the method as defined there. Basically, you are adding something to that method. It's what you typically do onCreate, for example.
In this case, returning false would mean that, if ID is different from the mentioned twos, we're done - menu managing can stop here. Obviously we are not, as we want the fragment to receive its call.
So: your activity overrides the superclass method to manage the first two menu items, then calls the superclass method to keep things running and say hey, there might be something that has not be managed here.
I am developing an Android app and I am trying to put a menu item into the ActionBar.
It has enough space, so it shouldn't be on the overflow or anything.
In my menu.xml I have added that item + android:showAsAction="ifRoom|withText"
However, no matter how large the screen is, that damn menu will not show up on the ActionBar (although it is present in the menu, if the user presses a key).
Unfortunately I cannot post any full-code since I am under a non-disclosure agreement, but I will answer all questions.
The section where I inflate the menu:
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.drinks, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.done:
//stuff
}
return super.onOptionsItemSelected(item);
}
Since you have only a menu item, use this attribute instead: android:showAsAction="always".
EDIT Above works all the time if you're running the code on post Honeycomb. But, in order to run on pre-Honeycomb, according to developer article, you need to extend from ActionBarActivity, that means adding compatibility support v4 & v7 and set the following theme for your activity:
<activity android:theme="#style/Theme.AppCompat.Light" ... >
... or a Them.AppCompat theme. Or use one of your own that extends from these.
I see that it's possible to handle a tap on a icon menù item or by implementing
onOptionsItemSelected
inside the acivity, or by using
onMenuItemClickListener
like onclick listener on a button. When is better to use the fist one method, and when the second one?
Because for my opinion, using an external listener makes more modular the code, but create a new class, but using the first way don't create new class, but makes code less modular...
There are use cases other than the ones outlined below, but I'm putting in the general cases that come up regularly.
onOptionsItemSelected
If you're using Fragments, you may want to use onOptionsItemSelected and consider adding menu items to the Action Bar the way that is described in Adding items to the Action Bar.
What this describes is implementing onCreateOptionsMenu inside your Fragment. To make this happen, you must call setHasOptionsMenu in onCreate.
protected void onCreate(Bundle savedInstanceState) {
this.setHasOptionsMenu(true);
}
Setting this will actually make the Activity call onCreateOptionsMenu which allows you to add the menu items.
#Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
// add items corresponding to this Fragment
menu.add(...);
return true;
}
The reason I recommend this is that it allows you to put more of the menu handling code into your Fragment instead of the Activity to figure out which Fragment to call, etc.
In this case, clicking the menu item will call onOptionsItemSelected inside of your Fragment which I suggest.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.my_id1:
dothing1();
return true;
case R.id.my_id2:
dotghing2();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
More of a long winded answer, but this is the way to handle menu clicks inside your Fragment.
onMenuItemClickListener
In the case of onMenuItemClickListener, this is used when you DON'T want to use the pre-ready method above and implement your own.
What I mean by that is you implement OnMenuItemClickListener and generate the methods in the interface. You then assign the menu to call the Activity that implemented this where as the above option assumes what Activity to use based on the pre-ready implementation of the Activity to Fragment relationship.
If you are targeting API 14 or greater (ICS or above) you could implement an ActionProvider. If that's not an option then you could implement a base activity that will always populate the menu and handle any menu clicks using onOptionsItemSelected. This is a good approach to implement "About" or "Settings" menu items through all your activities.
I'm having an issue connected with actions oferflow. On mdpi device with Android 2.3 on board, when I put two actions on the action bar and then add a ShareActionProvider it overflows to be under hardware menu button instead the overflow icon.
What is happening is partially acceptable, but the ShareActionProvider does not work at all under those circumstances. When I roll over the menu panel and click nothing happens.
Oh, I'm using AB Sherlock 4.2.0.
Do you know any workaround?
Thanks!
Current workround for me is to handle generic onOptionsItemSelected for provider's ID and do as follows:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
[...]
case R.id.menu_item_share:
startActivity(Intent.createChooser(mShareIntent, getString(R.string.share_title)));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
But it'd be nice to see this fixed. :)
I have been used this example, in this example you have to add /libs/android-support-v4.jar library file and and put a break point on public boolean onMenuItemSelected(int featureId, MenuItem item) method in /src/android/support/v4/app/Watson.java
line no. 115
debug source code when you use app for lower version api where "Menu" button exist.
Hope you will be able to find problem.
This topic can look similar to others but I haven't found any usable answer for this case.
Here is what I want : I have a TabActivity with a menu, containing tabs without any menu. When I press the menu button, I want the only existing menu to be displayed. If I only inflate the menu, this is working fine. But if I want to change the content of the menu (change the visibility of items in the onPrepareOptionsMenu(menu) method) or even press the items of the menu, nothing works.
For the onPrepareOptionsMenu(menu), the problem seems to be coming from the menu.findItem(...) method which returns a null Object, and I have a NullPointerException !
In onOptionsItemSelected(item), none of the item IDs will be recognized.
I have noticed with the debugger that the menu Context is the activity of the current tab, so I have moved the menu inside of that activity instead, but without more success.
Last thing, I was using the same menu and very similar code in a previous version of the app, using a single activity (no tabs) and I didn't encounter any problem. When I moved to the TabActivity design it was first working fine (maybe the context of the menu was my TabActivity instead of the Activity of the tab), but it didn't work anymore after minor changes to the Activities of the tabs (nothing related to any menu).
If you think using ActionBar (and the support package) would fix this, I am already planning in moving to it later, but I would like to understand and fix this first.
Here is the code :
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
MenuItem connect1 = menu.findItem(R.id.connect_1);
MenuItem connect2 = menu.findItem(R.id.connect_2);
// Here I do some stuff to prepare the menu, which could be simplified
// like this :
if (device1Connected)
if (!connect1.isVisible()) // here I get the NullPointerException
connect1.setVisible(true);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle item selection
switch (item.getItemId()) {
case R.id.select_device:
// do some stuff
return true;
case R.id.connect_1:
// do some stuff
return true;
case R.id.connect_2:
// do some stuff
return true;
case R.id.disconnect:
// do some stuff
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Here is the XML file of the menu, nothing special
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/select_device"
android:icon="#drawable/icon"
android:title="#string/choose_devices"/>
<item android:id="#+id/connect_1"
android:icon="#android:drawable/ic_menu_add"
android:title="#string/connect_1" />
<item android:id="#+id/connect_2"
android:icon="#android:drawable/ic_menu_add"
android:title="#string/connect_2" />
<item android:id="#+id/disconnect"
android:icon="#android:drawable/ic_menu_close_clear_cancel"
android:title="#string/disconnect" />
</menu>
Edit : I have added the following in the onPrepareOptionsMenu(menu) to avoid the NullPointerException. It doesn't fix the real problem but I can now see precisely what happens when I click on a MenuItem
if (connect1 == null || connect2 == null)
return super.onPrepareOptionsMenu(menu);
When I click on the first item, getItemId() returns, for example, 2131165207, and the second item returns 2131165208 (I have checked, they are ids of Views of the second tab !!), but the values it should return to enter the switch/case are respectively 2131165215 and 2131165216, so as I said before, I have a problem with my item ids. I made this test with the menu within the Activity of the first tab, because the mContext value of the menu is always an instance of the current Activity. But even though the Context AND the Activity containing the menu are the same, it still doesn't work.
So ! I have finally figured out what was wrong. It was a building/compiling error. I have been trying before refreshing the project many time, but it was not enough, I had also tried deleting the R.java file (where are compiling the ID numbers from the XML files), but it still didn't work; and I finally remembered about the Project -> Clear... function in Eclipse while working on another project.
And it just worked. So that was nothing there very challenging, but at least I've learnt something valuable today.