Android menuitem onclick handler's return value
Asked Answered
V

1

6

In android when I define a menuitem's onclick handler in xml

<item
    android:id="@+id/context_menu"
    android:orderInCategory="100"
    android:showAsAction="never"
    android:title="@string/word_context_menu_title"
    android:onClick="deleteItem"/>

And in the corresponding activity I define a function deleteItem with the below signature.

public boolean deleteItem(MenuItem item){
    logger.info("delete button clicked");
    return false;
}

My question is what does the return value signify? In which case should I return true and in which case should I return false?

Vinaya answered 19/4, 2014 at 13:34 Comment(0)
L
7

What the boolean return value means from the documentation of onMenuItemClick:

Return true to consume this click and prevent others from executing.

So similar behaviour to onOptionsItemSelected with the answer here. If I understand it correctly, this means that whenever you have successfully handled the event, you should return true.


Here's an example.

Say you have your deleteItem and also onOptionsItemSelected.

public boolean deleteItem(MenuItem item){
    Log.v("test", "delete button clicked");
    return false;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId())
    {
        case R.id.context_menu:
            Log.v("test","onOptionsItemSelected");
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

If you return false in deleteItem you will see that it is also handled in onOptionsItemSelected.

>delete button clicked
>onOptionsItemSelected

If you return true in deleteItem it will no longer be handled in onOptionsItemSelected.

>delete button clicked

Also note that your deleteItem handle can be a void method and it will automatically return true as per the source code here.

Landel answered 19/4, 2014 at 22:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.