Eldhose M Babu
Eldhose M Babu

Reputation: 14520

How to get ondetached event for a dialog fragment?

I've a situation like from my fragment activity, I need to do some operations when the fragment got detached from the fragment activity.

I know I can check for isDetached(), but i need to call some operations when the fragment got detached. Thanks...

Upvotes: 0

Views: 1817

Answers (1)

Marco RS
Marco RS

Reputation: 8245

You can create an interface in your Dialog Fragment that your activity must implement. In your Dialog Fragment you can override the "onDetach" method and call the listener activity in that method.

So something along these lines:

import android.app.Activity;
import android.support.v4.app.DialogFragment;

public class MyDialogFragment extends DialogFragment{

    public interface CallBack{
       public void onMyDialogFragmentDetached();
    }

    public CallBack mCallBack;

    @Override
    public void onAttach(Activity activity){
       super.onAttach(activity);
       mCallBack = (CallBack) activity;
    }

    @Override
    public void onDetach(){
       super.onDetach();
       mCallBack.onMyDialogFragmentDetached();
    }

}

Then just have your activity implement MyDialogFragment.CallBack:

  public class MyActivity extends Activity implements MyDialogFragment.CallBack{

    @Override
    public void onMyDialogFragmentDetached(){
       /** Called When MyDialogFragment gets detached. */
    }

  }

I hope that helps. Best of luck.

Upvotes: 3

Related Questions