【问题标题】:Is it possible to add method invoked by clicking on a button in Android (not adding listener)是否可以添加通过单击 Android 中的按钮调用的方法(不添加侦听器)
【发布时间】:2014-04-20 05:05:00
【问题描述】:

我想在单击按钮时调用方法。我找到了这个解决方案

Button buttonOne = (Button) findViewById(R.id.button1);
buttonOne.setOnClickListener(new Button.OnClickListener() {
    public void onClick(View v) {
            //Do stuff here
    }
});

但这个解决方案很糟糕。

在以下情况下是否可以在 XML 中添加方法调用:

  <Button
        android:id="@+id/actionButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/actionButtonUnclicked" 
        />

被点击?在 Windows Phone 和 WPF 的 XAML?类似android:onClick=clickMethod()

【问题讨论】:

    标签: android wpf button click


    【解决方案1】:

    您可以使用 android:onClick="clickMethod" 在 xml 中添加方法 在xml中:

      <Button
                android:id="@+id/actionButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/actionButtonUnclicked" 
        android:onClick="clickMethod"
                />
    
    
    and in activity/ fragment add
    

    你的方法应该收到 View v

    public void clickMethod(View v){
        // do smth
        }
    

    PS:如果你想对多个按钮使用相同的方法

     public void clickMethod(View v){
            // check for id
           if(v.getId() == R.id.button1){
    //operation for button 1 click
    } else if(v.getId() == R.id.button2){ //operation for button 1 click
    }
            }
    

    【讨论】:

      【解决方案2】:

      这里:

      <?xml version="1.0" encoding="utf-8"?>
      <!-- layout elements -->
      <Button android:id="@+id/actionButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click me!"
        android:onClick="myButtonClick" />
      <!-- even more layout elements -->
      

      在你的班级里:

      public void myButtonClick(View v) {
         // does something very interesting
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-10-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-30
        • 2015-07-02
        相关资源
        最近更新 更多