6

Every time I attach a fragment to my activity, I want to register it to receive events from the activity. This is easy, because I can override FragmentActivity#onAttachFragment(Fragment). When the fragment is removed from the activity, I want to unregister it from receiving events. I expected there to be a onDetachFragment event that I could use in a similar manner, but I'm not finding it.

Is there another way to accomplish what I'm trying to do? I'd like to keep the registering/unregistering in the activity, as opposed to moving it to a base fragment class (where I could just use onAttach/onDetach).

Edward Dale
  • 29,597
  • 13
  • 90
  • 129
  • its better to use the onStart(), onStop() method from your fragment. Just cast getActivity() to your calling activity class. – Anis BEN NSIR Sep 28 '12 at 08:32
  • @Anis It looks like that's the only way available. If you make your comment an answer, I'll accept it. – Edward Dale Nov 02 '12 at 12:42
  • I'm sorry for the following rant, but I just want to add that today, July 2018, I'm casually facing a trivial problem that I would be able to solve with a single line, were onDetachFragment available. Instead, I need to write, test and debug several convoluted lines of boilerplate code. – sigsegv Jul 25 '18 at 13:09

1 Answers1

-1

its better to use the onStart(), onStop() method from your fragment. Just cast getActivity() to your calling activity class.

Anis BEN NSIR
  • 2,555
  • 20
  • 29
  • Can you please explain why that is better? – Laimiux Sep 13 '16 at 16:50
  • its better because at this stage the fragment is attached to its parent activity. – Anis BEN NSIR Sep 15 '16 at 10:33
  • 2
    Wouldn't it be better design for parent to set the listeners on the fragment vs the fragment grabbing the listeners from the parent? – Laimiux Sep 16 '16 at 15:50
  • Or... cast it to the fragment's expected "listener" type (provided the attached Context/Activity passes the `instanceof` check) and your fragment doesn't have to know anything about your activity. Your fragment's onAttach/onDetach methods would be a great spot for this. – droid256 Dec 17 '17 at 21:45