How to Define Callbacks in Android?

后端 未结 6 1023
太阳男子
太阳男子 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:06

    Example to implement callback method using interface.

    Define the interface, NewInterface.java.

    package javaapplication1;

    public interface NewInterface {
        void callback();
    }
    

    Create a new class, NewClass.java. It will call the callback method in main class.

    package javaapplication1;
    
    public class NewClass {
    
        private NewInterface mainClass;
    
        public NewClass(NewInterface mClass){
            mainClass = mClass;
        }
    
        public void calledFromMain(){
            //Do somthing...
    
            //call back main
            mainClass.callback();
        }
    }
    

    The main class, JavaApplication1.java, to implement the interface NewInterface - callback() method. It will create and call NewClass object. Then, the NewClass object will callback it's callback() method in turn.

    package javaapplication1;
    public class JavaApplication1 implements NewInterface{
    
        NewClass newClass;
    
        public static void main(String[] args) {
    
            System.out.println("test...");
    
            JavaApplication1 myApplication = new JavaApplication1();
            myApplication.doSomething();
    
        }
    
        private void doSomething(){
            newClass = new NewClass(this);
            newClass.calledFromMain();
        }
    
        @Override
        public void callback() {
            System.out.println("callback");
        }
    
    }
    

提交回复
热议问题