简体   繁体   English

在 Android 中使用匿名类

[英]Working with anonymous class in Android

I'm an android beginner, I have some java knowledge, but i'm getting trouble with some android code.我是一个 android 初学者,我有一些 java 知识,但是我遇到了一些 android 代码的问题。

In java we can use anonymous class to override methods of an interface.在java中,我们可以使用匿名类来覆盖接口的方法。

I came across the following situation.我遇到了以下情况。

MyButton.setOnClickListener(New Button.OnClickListener{
    @override
    public void onClick(View view){
      //some code
    }
});

I was used to using the anonymous class like so,我习惯于像这样使用匿名类,

Interface myInterface = new Interface(){
}

I can't just figure out what only New followed by the interface name means,inside a method.我无法弄清楚只有 New 后跟接口名称的含义,在方法中。

It is a anonymous class without a variable name它是一个没有变量名的匿名类

MyButton.setOnClickListener(new Button.OnClickListener{
    @override
    public void onClick(View view){
        //some code
    }
});

is the same as是相同的

Button.OnClickListener listener = new Button.OnClickListener{
    @override
    public void onClick(View view){
        //some code
    }
});

MyButton.setOnClickListener(listener);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM