Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should be returned, true or false for onOptionsItemSelected() ?

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:

  • What should I return and why?

Thanks

like image 237
Alfred James Avatar asked Aug 12 '12 10:08

Alfred James


People also ask

What does the onOptionsItemSelected () method do?

2.2. If an action is selected, the onOptionsItemSelected() method in the corresponding activity is called. It receives the selected action as parameter.

What is onCreateOptionsMenu in Android?

onCreateOptionsMenu() is called by the Android runtime when it need to create the option menu. Android Developer Guide: Menus.


1 Answers

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.

like image 121
Madushan Avatar answered Oct 09 '22 21:10

Madushan