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

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

问题描述

我有麻烦理解这个code。我得到的帽子findViewById将获得按钮控件,然后它会投它。然后它的会使用BTN调用setOnClickListener方法。不过,我不知道什么被传递到setOnClickListener这样的说法,我从来没有见过code像之前。它是如何创建一个新的对象,但能够创建自己的另一种方法的参数中的一个方法?将是巨大的,如果有人能解释。还什么类型的对象是setOnClickListener方法服用吗?

  BTN =(按钮)findViewById(R.id.firstButton);
btn.setOnClickListener(新View.OnClickListener()
{
    @覆盖
    公共无效的onClick(视图v)
    {
        tv.setText(月[rand.nextInt(12)]);
        tv.setTextColor(Color.rgb(rand.nextInt(255)+1 rand.nextInt(255)+1 rand.nextInt(255)+1));
    }
});


解决方案

它的工作原理是这样的。 View.OnClickListenere定义 -

 公共接口OnClickListener {
    无效的onClick(视图V);
}

据我们所知,你不能实例化一个对象 OnClickListener ,因为它不具备实现的方法。因此,有两种方法可以通过去 - 你可以实现这个接口将覆盖的onClick 的方法是这样的:

 公共类myListener的实现View.OnClickListener {
    @覆盖
    公共无效的onClick(视图v){
         //你的code在这里;
    }
}

但它的繁琐,只要你想设定一个点击监听,每次去做。所以为了避免这种情况可以提供对点的方法的实施,就像在你举了一个例子。

setOnClickListener 需要 View.OnClickListener 作为它的参数。

I have trouble understand this code. I get hat findViewById will get the button widget and then it'll cast it. Then it's gonna use the btn 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 can 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));
    }
});

解决方案

It works like this. View.OnClickListenere is defined -

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

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.

setOnClickListener takes View.OnClickListener as its parameter.

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

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