Android的 - 如何设置button.setOnClickListener一个名为()的方法如何设置、方法、Android、setOnClickListener

2023-09-08 09:40:04 作者:诗酒趁年少

这是我看到出现在像button.setOnClickListener调用使用匿名方法()大多数样品。相反,我想在我在我工作的Activity类中定义的方法来传递。什么是C#中的Java / Android的下列事件处理布线等同?

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;

其中:

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.

推荐答案

罗马Nurik的答案几乎是正确的。 View.OnClickListener()实际上是一个接口。所以,如果你的活动实现OnClickListener,你可以将其设置为按钮单击处理程序。

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.
      }
}

有没有代表为在.NET中,让你在使用基于接口的功能卡。在.NET中,你可以通过使用代表指定不同的功能。

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.