How to recreate the listener passed to DialogFragment after orientation change?

I have some DialogFragmentthat do some work with the help listenerthat I pass on to her when I create it. Listener is an instance Fragmentthat implements the required interface. Everything is fine, but when you change the orientation everything is recreated, and I skip listener, so I just stumble upon NullPointeException. How to cope with this situation? Should I just close DialogFragmentif the orientation changes? I don’t think users will like this behavior. So I need to recreate listener... but how?

+5
source share
1 answer

Why not use the method Fragment#setTargetFragment. In this way

public class Fragment1 extends Fragment {
    ...
    public void createFragment2(){
        final Fragment dialogFragment = new MyDialogFragment();
        dialogFragment.setTargetFragment(this);
        dialogFragment.show();
    }
}


public class Fragment2 extends DialogFragment{
    ...
    public void onEvent(){
        ((Fragment1)getTargetFragment()).onEvent();
    }
}
+3

All Articles