简体   繁体   中英

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.

In java we can use anonymous class to override methods of an interface.

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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