Show dialog only using Context instead of Activity

2019-03-17 02:04发布

I could show dialog if I uses an Activity instance but when I uses Context or Application Context instance Dialog is not showing.

AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setTitle(title);
            builder.setMessage(msg);

            if (null != positiveLabel) {
                builder.setPositiveButton(positiveLabel, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        dialog.cancel();
                        if (null != listener) {
                            listener.onOk();
                        }
                    }
                });
            }

            if (null != negativeLable) {
                builder.setNegativeButton(negativeLable, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        dialog.cancel();
                        if (null != listener) {
                            listener.onCancel();
                        }
                    }
                });
            }

            builder.create().show();

Can you please give me a solution to show dialog without using Activity instance

3条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-03-17 02:35

The problem is something I faced recently too, you cant create a dialog without and activity instance. getApplicationContext() call doesn't work too. The way I did this is to make the call to a method that creates the dialog, from an activity, and pass "this" i.e. the reference to that activity as a parameter.

If you are going to reuse this code, as a reusable component or as a mechanism to create dialogs at multiple places, create a base activity class and have this method in there, and use it in sub-classed activities as needed.

查看更多
可以哭但决不认输i
3楼-- · 2019-03-17 02:47

For some reason [at least in android 2.1] a toast can be on the application context but not a progress dialog

MyActivity.this is an activity specific context which does not crash

MyActivity.getApplicationContext() is global and will crash progress bars and in later versions also toasts.

查看更多
放荡不羁爱自由
4楼-- · 2019-03-17 02:48

This is one of the MOST important things that you must always remember about Contexts. There are 2 types of contexts, Activity contexts and Application contexts. You will observe in many UI related classes, a Context is passed. This is not the Application context! In such cases you must always pass an Activity Context. Except for a Toast, no other UI component will work with Application context.

Application Context is always passed when you want some service or component which is Application related, like the Telephony Manager, Location Manager etc.

For UIs, you must always pass a context that is UI related which is the Activity.

查看更多
登录 后发表回答