Android menuitem onclick handler's return value

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-10 13:27:01

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/23170715/android-menuitem-onclick-handlers-return-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!