Android setOnClickListener 方法 - 它是如何工作的? [英] Android setOnClickListener method - How does it work?

查看:18
本文介绍了Android setOnClickListener 方法 - 它是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解这段代码.我知道 findViewById 将获得按钮小部件,然后它会投射它.然后,它将使用按钮调用 setOnClickListener 方法.但是,我不知道传递给 setOnClickListener 的参数是什么,而且我以前从未见过这样的代码.它如何创建一个新对象但能够在另一个方法的参数中创建自己的方法?如果有人能解释一下就好了.另外,setOnClickListener 方法接收的是什么类型的对象?

I have trouble understanding this code. I get that findViewById will get the button widget and then it'll cast it. Then, it's going to use the button to call the setOnClickListener method. However, I don't know what is that argument being passed into the setOnClickListener and I have never seen code like that before. How is it that it creates a new object but is able to create a method of its own within another method's argument? Would be great if someone could explain that. Also, what type of object is the setOnClickListener method taking in?

btn = (Button)findViewById(R.id.firstButton);
btn.setOnClickListener(new View.OnClickListener()
{
    @Override
    public void onClick(View v)
    {
        tv.setText(months[rand.nextInt(12)]);
        tv.setTextColor(Color.rgb(rand.nextInt(255)+1, rand.nextInt(255)+1, rand.nextInt(255)+1));
    }
});

推荐答案

它是这样工作的.View.OnClickListenere 已定义 -

It works like this. View.OnClickListenere is defined -

public interface OnClickListener {
    void onClick(View v);
}

据我们所知,您无法实例化对象 OnClickListener,因为它没有实现方法.所以有两种方法你可以去 - 你可以实现这个接口,它会像这样覆盖 onClick 方法:

As far as we know you cannot instantiate an object OnClickListener, as it doesn't have a method implemented. So there are two ways you can go by - you can implement this interface which will override onClick method like this:

public class MyListener implements View.OnClickListener {
    @Override
    public void onClick (View v) {
         // your code here;
    }
}

但是每次都要设置点击监听器很繁琐.因此,为了避免这种情况,您可以在现场提供该方法的实现,就像您提供的示例一样.

But it's tedious to do it each time as you want to set a click listener. So in order to avoid this you can provide the implementation for the method on spot, just like in an example you gave.

setOnClickListenerView.OnClickListener 作为参数.

这篇关于Android setOnClickListener 方法 - 它是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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