不同的OnClickListener实现方式 [英] The different OnClickListener implementation ways

查看:188
本文介绍了不同的OnClickListener实现方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么区别:

public class MainActivity extends Activity {

    public void onCreate (Bundle savedInstanceState) {
        button1 = (Button) findViewById(R.id.btn1);
        button1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // Click code
            }
        )};
    }
}

并且:

public class MainActivity extends Activity implements OnClickListener {

    public void onCreate (Bundle savedInstanceState) {
        button1 = (Button) findViewById(R.id.btn1);
        button1.setOnClickListener(this);
    }

    public void onClick(View arg0) {
        switch(arg0.getId()) {
        case R.id.button1:
            // Click code
            break;
        }
    }
}

它们都完全相同功能和结果。

They have both the exact same functionality and results.

推荐答案

第一种方法使用实现接口方法的匿名内部类。通过使用此方法,您只接收该特定View的事件。

The first method uses an anonymous inner class that implements the interface method. By using this approach, you receive events only for that particular View.

在第二种方法中,整个Activity类实现 OnClickListener 界面。您可以将每个View的OnClickListener设置为 this ,并在一个方法中接收所有点击事件,然后您可以在其中过滤它们并对其进行操作。

In the second method, you entire Activity class implements the OnClickListener interface. You can set the OnClickListener of every View to this, and receive all the click events in one method, where you can then filter them and act upon them.

第一种方法转换为:

Button.OnClickListener anonymous_listener = new Button.OnClickListener() { ... };
button.setOnClickListener(anonymous_listener);

这就是说它动态创建并存储一个新的 OnClickListener 使用它时的实例。

Which is to say that it dynamically creates and stores a new OnClickListener instance when you use it.

在第二种方法中,您的整个类使用 OnClickListener ,传递给你想要点击的所有视图。

In the second method, your entire class uses one single instance of the OnClickListener, that is passed to all the Views you want to listen for clicks on.

这篇关于不同的OnClickListener实现方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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