Android detect when fragment is detached
android
Solution
you can use interface for communicating between `Fragment` and `Activity`
something like this :
public Class MyFragment extends Fragment {
FragmentCommunicator communicator;
public void setCommunicator(FragmentCommunicator communicator) {
this.communicator = communicator;
}
@Override
public void OnDetach() {
communicator.fragmentDetached();
}
...
public Interface FragmentCommunicator {
public void fragmentDetached();
}
}
and in your activity :
public Class MyActivity extends Activity Implements FragmentCommunicator {
...
MyFragment fragment = new MyFragment();
fragment.setCommunicator(this);
...
@Override
public void fragmentDetached() {
//Do what you want!
}
}
Edit:
the new approach is setting interface instance in `onAttach`.
public void onAttach(Activity activity) {
if (activity instanceof FragmentCommunicator) {
communicator = activity;
} else {
throw new RuntimeException("activity must implement FragmentCommunicator");
}
}
now there is no need to have `setCommunicator` method.
Problem
I can easily detect when `Fragments` are attached to `Activity` via `Activity.onAttachFragment()` But how can I detect in `Activity` that some `Fragment` is detached from activity? There is no `Activity.onDetachFragment()` Is subcclasing `Fragment` and write some code to notify `Activity` about that state is the only solution?