Android setOnclicklistener参数 [英] Android setOnclicklistener parameter

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

问题描述

我是android的初学者,将onclick侦听器设置为按钮时,传递的参数是什么意思:

I'm a beginner to android, while setting onclick listener to a button, what does the parameter passed mean:

 btn1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

        }
    });    

因此,"new OnClickListener()"将其传递给方法,那么该方法不应该是对象吗?
如果它不是一个对象;那么我们如何使用新"关键字呢?
为什么不使用"this"关键字或其类名直接调用"onclick()".

so, "new OnClickListener()" it is passed to a method then shouldn't that be an object?
if it is not an object; then how do we use "new" keyword?
why "onclick()" is called directly without using the "this" keyword, or its class name.

推荐答案

OnClickListener 界面并使用 new OnClickListener()作为 btn1.setOnClickListener 的参数,它实际上是在创建 匿名内部类 ,它实现了 OnClickListener .而且必须声明方法 onClick ,因为该方法是该接口类中的抽象方法.按下按钮后,您在onClick内编写的任何代码都将执行.

OnClickListener is an interface and by using new OnClickListener() as parameter for btn1.setOnClickListener it is actually creating an Anonymous Inner Class which implements OnClickListener. And the method onClick must need to be declared since its an abstract method inside that interface class. Any code you write inside onClick will be executed when the button is pressed.

更新

使用对象中的匿名内部类来完成此操作:

to do it using Anonymous inner class in an object:

//declaring OnClickListener as an object
private OnClickListener btnClick = new OnClickListener() {
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

    }
};

//passing listener object to button
btn1.setOnClickListener(btnClick);

不使用匿名类就可以做到这一点:

to do it without using Anonymous class:

public class YourActivity extends Activity implements OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
       Button b = new Button(this);

       //setting listener to button
       b.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

    }
}

这两种方法之间的唯一区别是,如果您的按钮包含应该仅对该按钮有效/可用的点击事件代码,则您可以像在代码中一样使用内部类(因为它很容易做到)马上).但是,如果有多个按钮需要在onClick事件上执行相同的代码,则可以将侦听器定义为对象并将其传递给它们.

The only difference between these approaches is, if your button contains click event code which is supposed to be valid/available for that button only, then you may use inner class as you are doing in your code (because its easy to do right away). However if there are multiple buttons which require same code to be executed on onClick event then you may define listener as an object and pass it to them.

这篇关于Android setOnclicklistener参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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