質問

I have an Activity which shows a DialogFragment when an event occurs in the Activity. When my application is running the user can press home button to make the app run in background. When app is running in background, as soon as the event occurs, the activity should show the DialogFragment, so that when user resumes the app the dialog should be on top of the activity, however I am not getting the results I want. As soon as I resume the app from launcher icon or notification, the dialog does not appear on the activity.

Here is my DialogFragment class:

public static class MyDialog extends DialogFragment {

    public static DialogInterface.OnClickListener mListener;
    public static String mTitle, mBody;
    public static boolean mConfirm;

    public static MyDialog getInstance(String body, boolean confirm,
            DialogInterface.OnClickListener listener) {
        mListener = listener;
        mTitle = "MyDialog";
        mBody = body;
        mConfirm = confirm;
        MyDialog fragment = new MyDialog();
        return fragment;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedIntanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
        .setTitle(mTitle).setMessage(mBody)
        .setPositiveButton("Ok", mListener);
        if (mConfirm)
            builder.setNegativeButton("Cancel", mListener);
        return builder.create();
    }
}

The dialog works fine when activity is in foreground. Here is how I show the dialog:

MyDialog.getInstance("This is dialog body text", true, 
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == DialogInterface.BUTTON_POSITIVE) {
                            // positive button pressed
                        }else //negative button pressed
                    }
        }).show(getSupportFragmentManager(), "dialog");

I want a dialog that remains on the activity even if the activity is in background, and as soon as I resume the activity, the dialog should be on top of the activity. How can I achieve this behavior?

役に立ちましたか?

解決

You can declare a global boolean to determine if you should show the dialog or not. Then in your activity onResume() method you show the dialog depending on the boolean value.

If the user is finished interacting with the dialog you can set this boolean to false which will cause it not to show again when your activity is in the foreground (onResume).

他のヒント

Try using Fragment's or Activity's showDialog(int) methods and your dialog will be retained automatically.

Check out that link

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top