【问题标题】:How to get out from onClick method for Button Listener in Android如何摆脱Android中按钮监听器的onClick方法
【发布时间】:2016-07-04 15:38:36
【问题描述】:

考虑以下代码:

Button add_product_button = (Button) findViewById(R.id.add_product_button);
    add_product_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            //Before going further, we check whether all the information is provided or not
            EditText item_title_text = (EditText) findViewById(R.id.item_title);
            if(isEmpty(item_title_text)){
                break;
            }

我想要'休息;'成为我不想继续进行的响应(不执行其余代码并退出)。

这是为了提醒用户提供的信息不足。我怎样才能做到这一点?

【问题讨论】:

    标签: android onclicklistener


    【解决方案1】:

    如果所需信息不存在,我实际上会建议禁用您的按钮,以便用户无法单击它。您可以在任何对话框/视图上显示一条消息以通知用户需要信息,或者在 EditText 提示之后添加类似“(required)”的字符串。

    Button add_product_button = (Button) findViewById(R.id.add_product_button);
    EditText item_title_text = (EditText) findViewById(R.id.item_title);
    
    if(isEmpty(item_title_text)){
        add_product_button.setEnabled(false);
    }
    

    然而,如果您出于某种原因需要按照您描述的方式进行操作,要回答您如何“脱身”,您只需return out onClick 方法。

    if(isEmpty(item_title_text)){
        return;
    }
    

    在返回之前,您可以调用一些方法来执行您想做的任何事情(您自己的方法可能会向用户显示他们没有足够信息的消息)。

    if(isEmpty(item_title_text)){
        notifyUserOfEmptyField();
        return;
    }
    

    【讨论】:

      【解决方案2】:

      无需继续编写代码即可摆脱它

      if(isEmpty(item_title_text)){
          return;
      }
      

      您可能希望显示一个带有错误的 Toast:

      if(isEmpty(item_title_text)){
          Toast.makeText(...);
          return;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多