How to create our own Listener interface in android?

前端 未结 9 1902
不知归路
不知归路 2020-11-22 04:55

Could someone help me to create user defined listener interface with some code snippets?

9条回答
  •  伪装坚强ぢ
    2020-11-22 05:48

    Create a new file:

    MyListener.java:

    public interface MyListener {
        // you can define any parameter as per your requirement
        public void callback(View view, String result);
    }
    

    In your activity, implement the interface:

    MyActivity.java:

    public class MyActivity extends Activity implements MyListener {
       @override        
       public void onCreate(){
            MyButton m = new MyButton(this);
       }
    
        // method is invoked when MyButton is clicked
        @override
        public void callback(View view, String result) {   
            // do your stuff here
        }
    }
    

    In your custom class, invoke the interface when needed:

    MyButton.java:

    public class MyButton {
        MyListener ml;
    
        // constructor
        MyButton(MyListener ml) {
            //Setting the listener
            this.ml = ml;
        }
    
        public void MyLogicToIntimateOthers() {
            //Invoke the interface
            ml.callback(this, "success");
        }
    }
    

提交回复
热议问题