user1411335
user1411335

Reputation: 3590

How to close app if user presses back button on dialog

I am new to Android and developing a utility UI component which displays dialog box on launch , I want to close the app if user does not make a choice in the dialog box and chooses to press back button. How do I achieve this in dialogFragment? I would not have access to the activity code .

This component is implemented as DialogFragment.

I tried

    dialog.setOnDismissListener( new OnDismissListener()
    {
        @Override
        public void onDismiss(DialogInterface dialog)
        {
            getActivity().finish();
        }
    });

but this does not close the activity if I press back button.

what is the best practice to implement mandatory dialog box in Android

Thanks in advance

Upvotes: 0

Views: 1827

Answers (1)

Sabeer
Sabeer

Reputation: 4110

  1. Make a flag true when open the dialog...
  2. onBackPressed() check if the flag true...
  3. if true finish the activity...

I haven't tested but it may work ...

@Override
public void onDismiss(DialogInterface dialog)
{
            ((YourActivity)getActivity()).finish();
}

If the above one not working ... create a method in your activity for example ...

public void closeActivity(){

finish();

}

then call the function closeActivity() onDismiss

 @Override
    public void onDismiss(DialogInterface dialog)
    {
                ((YourActivity)getActivity()).closeActivity();
    }

Upvotes: 3

Related Questions