I was learning menu inflater and the tutorial I am following says we should return false in this function. However when I return true, I didn't notice any change or difference. So the question is:
Thanks
2.2. If an action is selected, the onOptionsItemSelected() method in the corresponding activity is called. It receives the selected action as parameter.
onCreateOptionsMenu() is called by the Android runtime when it need to create the option menu. Android Developer Guide: Menus.
If you want the normal processing to happen, return false. Otherwise, return true.
See Documentation.
By default, when you return false, Android calls the Runnable associated with the item or runs the Intent which you can set using setIntent(...)
on the MenuItem. If you don't want this to happen, you should return true.
Say you create the MenuItem as follows.
MenuItem menu1 = new MenuItem(this);
menu1.setIntent(myIntent);
Here myIntent
is what you want to do when the menu item is being clicked. For ex: say your menu item launches GMail app to send an email, with the text on a text view on your activity.
In your onOptionsItemSelected()
callback, you can check the value of the text view, and return false if the text view is not empty (you have something in the text box, you can fire the Intent
to GMail) otherwise show a message box saying "Please type a message first" and return true, so Android won't fire the Intent.
public boolean onOptionsItemSelected (MenuItem item) {
if (textView.getText().trim().equals("")){
// show the message dialog
return true;
}
else {
// we have some message. We can let android know that
// it is safe to fire the intent.
return false;
}
}
Hope this helps... Happy Coding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With