Search code examples
androidandroid-fragmentsdetach

Detach fragment not immediately


I have a little question. Currently I have a fragment. When detaching I want to show the user something like do you want to save the changes. But I want to call super.onDetach() after the user has selected an option. I tried to call super.onDetach() after an option but then I get an exception that super.onDetach() is not called when detaching. Any ideas?

Thanks in advance

This is my code :

@Override
public void onDetach() {


    DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch (which){

            case DialogInterface.BUTTON_POSITIVE:
                if(attachProfiel){
                    FragmentProfiel.updateProfiel();
                }
                if(attachDiagnose){
                    FragmentDiagnose.updateDiagnose();
                }
                if(attachAndere){
                    FragmentAndere.updateAndere();
                }
                break;

            case DialogInterface.BUTTON_NEGATIVE:
                break;
            }
        }
    };

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setMessage("Save changes?").setPositiveButton("Ja", dialogClickListener)
        .setNegativeButton("Nee", dialogClickListener).show();


}

OnDestroyView :

@Override
public void onDestroyView() {
    new ExitFragment(getActivity()).show(getFragmentManager(), "MyDialog");
    super.onDestroyView();

}

Solution

  • I would recommend that you call your DialogFragment() in onBackPressed() method, there by asking the user to save the preference. If you would like to reclaim the data that user entered in the fragment, then use SharedPreference in android. See http://developer.android.com/reference/android/content/SharedPreferences.html