Android - How to set a named method in button.setOnClickListener()

我是研究僧i 提交于 2019-12-23 07:03:50

问题


Most samples that I see appear to use an anonymous method in a call like button.setOnClickListener(). Instead, I'd like to pass in a method defined on the Activity class that I'm working in. What's the Java/Android equivalent of the following event handler wiring in C#?

Button myButton = new Button();
myButton.Click += this.OnMyButtonClick;

Where:

private void OnMyButtonClick(object sender, EventArgs ea)
{
}

Essentially, I'd like to reuse a non-anonymous method to handle the click event of multiple buttons.


回答1:


Roman Nurik's answer is almost correct. View.OnClickListener() is actually an interface. So if your Activity implements OnClickListener, you can set it as the button click handler.

public class Main extends Activity implements OnClickListener {

      public void onCreate() {
           button.setOnClickListener(this);
           button2.setOnClickListener(this);
      }

      public void onClick(View v) {
           //Handle based on which view was clicked.
      }
}

There aren't delegates as in .Net, so you're stuck using the function based on the interface. In .Net you can specify a different function through the use of delegates.




回答2:


The argument to View.setOnClickListener must be an instance of the class View.OnClickListener (an inner class of the View class).. For your use case, you can keep an instance of this inner class in a variable and then pass that in, like so:

View.OnClickListener clickListener = new OnClickListener() {
    public void onClick(View v) {
        // do something here
    }
};

myButton.setOnClickListener(clickListener);
myButton2.setOnClickListener(clickListener);

If you need this listener across multiple subroutines/methods, you can store it as a member variable in your activity class.




回答3:


The signature of the method will need to be this...

public void onMyButtonClick(View view){

}

If you are not using dynamic buttons, you can set the "onClick" event from the designer to "onMyButtonClick". That's how I do it for static buttons on a screen. It was easier for me to relate it to C#.



来源:https://stackoverflow.com/questions/1972579/android-how-to-set-a-named-method-in-button-setonclicklistener

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