Android setOnClickListener方法-如何工作? [英] Android setOnClickListener method - How does it work?
问题描述
我在理解此代码时遇到了麻烦.我知道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.
setOnClickListener
将View.OnClickListener
作为其参数.
这篇关于Android setOnClickListener方法-如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!