Android menuitem onclick处理程序的返回值 [英] Android menuitem onclick handler's return value

查看:296
本文介绍了Android menuitem onclick处理程序的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在android中,我在xml中定义menuitem的onclick处理程序

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"/>

然后在相应的活动中,定义一个带有以下签名的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;
}

我的问题是返回值表示什么?在哪种情况下我应该返回true,在哪种情况下我应该返回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?

推荐答案

boolean返回值的含义来自

返回true以消耗此点击并阻止其他点击执行.

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

行为与onOptionsItemSelected类似,答案为此处.如果我对它的理解正确,则意味着每当成功处理该事件时,都应返回true.

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.

这是一个例子.

假设您有deleteItemonOptionsItemSelected.

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);
    }
}

如果在deleteItem中返回false,则会看到它也在onOptionsItemSelected中得到处理.

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

>删除按钮已点击
> onOptionsItemSelected

>delete button clicked
>onOptionsItemSelected

如果在deleteItem中返回true,它将不再在onOptionsItemSelected中处理.

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

>点击删除按钮

>delete button clicked

还请注意,您的deleteItem句柄可以是void方法,它将根据源代码这里.

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

这篇关于Android menuitem onclick处理程序的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆