Android的 - 如何设置button.setOnClickListener一个名为()的方法 [英] Android - How to set a named method in button.setOnClickListener()

查看:182
本文介绍了Android的 - 如何设置button.setOnClickListener一个名为()的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我看到出现在像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.

这篇关于Android的 - 如何设置button.setOnClickListener一个名为()的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆