Save Interface (listener) In Onsaveinstancestate
SaveInstanceState For data like Integer, Long, String and else are fine, I just put it in the bundle and get it back once the onCreateView gets called again. But my fragment also h
Solution 1:
I recently just found the proper way to do this and I want to share for future reader of this topic.
The proper way to save listener of the fragment is not to save it, but instead, request from activity when fragment got attached to activity.
publicclassTheFragmentextendsFragment {
private TheFragmentListener listener;
@Override
publicvoidonAttach(Context context) {
if (context instanceof TheFragmentContainer) {
listener = ((TheFragmentContainer) context).onRequestListener();
}
}
publicvoidtheMethod() {
// do some taskif (listener != null) {
listener.onSomethingHappen();
}
}
publicinterfaceTheFragmentContainer {
public TheFragmentListener onRequestListener();
}
publicinterfaceTheFragmentListener {
publicvoidonSomethingHappen();
}
}
- when the fragment attach to an activity, we check if activity implement TheFragmentContainer or not
- if the activity does, request listener from activity.
Post a Comment for "Save Interface (listener) In Onsaveinstancestate"