【问题标题】:How to determine which button pressed on android如何确定在android上按下了哪个按钮
【发布时间】:2017-02-10 21:22:05
【问题描述】:

我需要知道如何识别按下了哪个按钮。 就像我有两个按钮,比如按钮 1 和按钮 2,并且它们都执行相同的方法,比如 method(),如何确定按下了哪个按钮?

问候

【问题讨论】:

    标签: android


    【解决方案1】:

    最优雅的模式:

    public void onClick(View v) {
    switch(v.getId())
    {
    case R.id.button_a_id:
    // handle button A click;
    break;
    case R.id.button_b_id:
    // handle button B click;
    break;
    default:
    throw new RuntimeException("Unknow button ID");
    }
    

    这样调试起来就简单多了,确保不会错过处理任何点击。

    【讨论】:

      【解决方案2】:

      我有 10 个按钮执行相同的方法updateText(),我使用此代码获取单击按钮的文本:

      public void updateText(View v){
          Button btn = (Button) findViewById(v.getId());
          String text = btn.getText().toString();
      }
      

      【讨论】:

        【解决方案3】:

        或者...您可以在 xml 代码中添加一个 android:onClick="foo" 按钮,并使用签名在 java 上定义一个方法。在 - 的里面 方法 foo,获取 id 并将其与您需要的进行比较

        public void foo(View v){
        
        if (v.getId() == R.id.yourButton){
        
        }
        
        else if (v.getId() == R.id.nextButton){
        
        }
        
        }
        

        【讨论】:

          【解决方案4】:

          如果“执行相同的方法”是指他们的 OnClickListener,那么您必须引用传递给它的参数。

          public void onClick(View v) {
              if(v==btnA) {
                 doA();
              } else if(v==btnB) {
                 doB();
              }
          }
          

          【讨论】:

            【解决方案5】:

            好的,解决方法

            if (yesButton.getId() == ((Button) v).getId()){
            
              // remainingNumber
             }
            
            else if (noButton.getId() == ((Button) v).getId()) 
            {
                // it was the second button
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2016-01-27
              • 2010-12-05
              • 2015-12-11
              • 1970-01-01
              • 1970-01-01
              • 2013-10-17
              • 2014-02-04
              • 2016-06-16
              相关资源
              最近更新 更多