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

I studied by inflating the menu, and the tutorial that I follow says that we should return false in this function. However, when I return, I did not notice any changes or differences. So the question is:

  • What should I return and why?

thanks

+4
source share
2 answers

If you want normal processing to happen, return false. Otherwise, return true.

See the documentation .

By default, when you return false, Android calls the Runnable associated with the element, or starts an Intent, which you can set using setIntent(...) in MenuItem. If you do not want this to happen, you must return true.

Suppose you create a MenuItem as follows.

 MenuItem menu1 = new MenuItem(this); menu1.setIntent(myIntent); 

Here myIntent is what you want to do when a menu item is clicked. For example: your menu item launches the GMail application to send an email with text in a textual representation of your activity.

In the onOptionsItemSelected() 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 field, you can run Intent in GMail), otherwise show a window with the message "Please enter message first "and return true, so Android will not trigger 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.

+12
source

if you are handling the return true event, otherwise return false

+3
source

All Articles