1

I am trying to implement a void method callback inside an anonymous class and I am a bit lost with the syntax since I working on a large android code-base. I have set a listener to and image button like so:

MyImageView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        OnFollowingClick click;
        click = new OnMyClick(param1, param2);  // irrelevant for this thread
        click.onClick(view);    // irrelevant for this thread

        // my problem is here!
        click.setCallback( what do I pass in here? and where can define my callback?);
    }
});

Here is the OnMyClick class and the void callback interface I defined:

public interface CallbackInterface {
    public void Callback();
}

public class OnMyClick implements View.OnClickListener {
    // I added this
    CallbackInterface mCallBack;
    public void setCallback(CallbackInterface callback) {
        this.mCallBack = callback;
    }
    // Please call my callback
    public void onFollowingChanged() {
        if (mCallBack != null) {
            mCallBack.Callback();
        }
    }
    // a bunch of code in here that does not matter
    // ...

I have to create callback somewhere, so I am guessing I need something like:

public class SomeClass implements CallbackInterface {

    @Override
    public void Callback() {
        System.out.println("Hey, you called.");
    }
}

The problem is that listener is an anonymous function, so I don't want to define a separate class somewhere just to serve as a callback.

I looked at this thread but did not give me much info:

How can an anonymous class use "extends" or "implements"?

is there a way to make the anonymous function implement my interface inside the scope, like:

MyImageView.setOnClickListener(new View.OnClickListener() {

    @Override
    public void Callback() {
        // please call me!
    }

Not sure if it made sense, buy any help is greatly appreciated.

thx!

Community
  • 1
  • 1
gmmo
  • 2,577
  • 3
  • 30
  • 56

1 Answers1

0

Just define the callback anonymously like you are already doing with the View.OnClickListener.

MyImageView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        OnFollowingClick click;
        click = new OnMyClick(param1, param2);  // irrelevant for this thread
        click.onClick(view);    // irrelevant for this thread

        // your solution is here!
        click.setCallback(new CallbackInterface() {
            @Override
            public void Callback() {
                System.out.println("Hey, you called.");
            }
        });
    }
});

If this is not what you meant then please clarify and I will try and help further.

George Mulligan
  • 11,813
  • 6
  • 37
  • 50