A
A
Alina Mitrokhina2019-09-08 18:07:28
Java
Alina Mitrokhina, 2019-09-08 18:07:28

How to properly initialize a Listener in an Activity?

Good afternoon, there was a task to throw the Listener from the Fragment into the Activity. With the reverse task, everything is simple. I just implement the callback methods onAttach and onDetach. But how to do the opposite? More precisely, how to do it right?

override fun onAttach(context: Context) {
        super.onAttach(context)
        if(context is OnCityChangeListener) {
            listener = context
        }
    }

    override fun onDetach() {
        super.onDetach()
        listener = null
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
tiroman, 2019-09-09
@fursa08

I would implement using EventBus, both ways

D
Denis Zagaevsky, 2019-09-08
@zagayevskiy

Make a ListenerHolder interface with add/removeListener methods, implement it in an activity. In the fragment, cast an activity to this interface and poke yourself into it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question