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?
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.
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