How to Define Callbacks in Android?

后端 未结 6 1032
太阳男子
太阳男子 2020-11-22 05:32

During the most recent Google IO, there was a presentation about implementing restful client applications. Unfortunately, it was only a high level discussion with no source

6条回答
  •  别那么骄傲
    2020-11-22 06:05

    In many cases, you have an interface and pass along an object that implements it. Dialogs for example have the OnClickListener.

    Just as a random example:

    // The callback interface
    interface MyCallback {
        void callbackCall();
    }
    
    // The class that takes the callback
    class Worker {
       MyCallback callback;
    
       void onEvent() {
          callback.callbackCall();
       }
    }
    
    // Option 1:
    
    class Callback implements MyCallback {
       void callbackCall() {
          // callback code goes here
       }
    }
    
    worker.callback = new Callback();
    
    // Option 2:
    
    worker.callback = new MyCallback() {
    
       void callbackCall() {
          // callback code goes here
       }
    };
    

    I probably messed up the syntax in option 2. It's early.

提交回复
热议问题