Using anonymous classes when calling interfaces

I am trying to fully integrate the concept of anonymous classes and interfaces in Android and Java. In another thread, an answer was given to a question about something like:

getQuote = (Button) findViewById(R.id.quote);

getQuote.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        // Do something clever
    }
}

"What is sent in an anonymous class, you can also make a separate class that implements OnClickListener and instantiates this class and sends it as an argument to setOnClickListener." - John

My question is, what would the code look like if you went the long way to create a separate class that implements OnClickListener? I think if I saw a long route, it would make more sense. Many thanks!

+3
source share
4 answers
class MyClass implements View.OnClickListener {

    @Override
    public void onClick(View v) {

        // Do something clever
    }

}

// Calling Code

MyClass listener = new MyClass();
getQuote.setOnClickListener(listener);

, , , .

+3
//somewhere in your class or even as its own top-level class:
static class MyOnClickListener implements View.OnClickListener {

    @Override
    public void onClick(View v) {
        // Do something clever
    }
}

getQuote.setOnClickListener(new MyOnClickListener());

, . , static ( ).

+3

:

getQuote = (Button) findViewById(R.id.quote);
getQuote.setOnClickListener(new MyClickListener(param));

// in a separate class file:    
public class MyClickListener extends View.OnClickListener{
    private Param param;

    public MyClickListener(Param p){
        this.param = p;
    }

    @Override
    public void onClick(View v) {
        // Do something clever with param
    }
}

, , , .

+3

, ( ), , .

:

public class MyOnClickListener implements View.OnClickListener {
    public void onClick(View v) {
        //do something
    }
}

Here is the built-in class:

public class MyActivity extends Activity {

    class MyOnClickListener implements View.OnClickListener {
        public void onClick(View v) {
            //do something
        }
    }
}
+1
source

All Articles