How do I make the AlertDialog box appear outside the app?

亡梦爱人 提交于 2019-11-27 16:28:01

Add a line as:

public void ShowDialog() {
    final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);

    alertDialog.setTitle("REMINDER!");
    alertDialog.setMessage("Turn off alarm by pressing off");

    alertDialog.setNegativeButton("Off", new DialogInterface.OnClickListener(){
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(getApplicationContext(), "OFF", Toast.LENGTH_SHORT).show();
        }
    });

    alertDialog.show();
    // line you have to add
    alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST);
}

check now.

Ishaan

Do not accept answers if they don't address your question, it is misleading.

The accepted answer is not correct, as it will never work outside your application.

Reason:

  1. It requires an activity context not application context.

  2. If you provide application context, your app will crash with IllegalArgumentException- you need to use Theme.AppCompat or their decendents...

If you need functionality as actually stated in the question you have to have a separate activity themed as a Dialog like here

or you can add a custom view to your window using window manager and making it system level alert like here.

Do this create an Activity without ContentView or a View associated with it and call your alertDialog method in your onCreate also remember to set the background of the Activity to Transparent using ColourDrawable

And that activity will look like a dialog or will suit your preference, you can also fall back to Themes so you can set an Activity as Dialog and treat it like Dialog also use DialogFragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!