Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 504
James Cadd Avatar asked Dec 29 '09 02:12

James Cadd


2 Answers

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.

like image 200
GrkEngineer Avatar answered Oct 12 '22 12:10

GrkEngineer


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.

like image 27
Roman Nurik Avatar answered Oct 12 '22 13:10

Roman Nurik