How to create our own Listener interface in android?

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

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

9条回答
  •  無奈伤痛
    2020-11-22 05:41

    In the year of 2018, there's no need for listeners interfaces. You've got Android LiveData to take care of passing the desired result back to the UI components.

    If I'll take Rupesh's answer and adjust it to use LiveData, it will like so:

    public class Event {
    
        public LiveData doEvent() {
             /*
              * code code code
              */
    
             // and in the end
    
             LiveData result = new MutableLiveData<>();
             result.setValue(eventResult);
             return result;
        }
    }
    

    and now in your driver class MyTestDriver:

    public class MyTestDriver {
        public static void main(String[] args) {
            Event e = new Event();
            e.doEvent().observe(this, new  Observer() {
                @Override
                public void onChanged(final EventResult er) {
                    // do your work.
                }
            });
        }
    }
    

    For more information along with code samples you can read my post about it, as well as the offical docs:

    When and why to use LiveData

    Official docs

提交回复
热议问题