Android自定义对话框出错

时间:2013-12-26 04:59:58

标签: java android eclipse android-layout android-dialog

在我的 android 应用中,我必须在按钮点击事件上弹出对话框。但是当我点击按钮时,应用停止工作。我将预先设计的布局加载到对话框中。我将发布一个代码段。

Button login = (Button) findViewById(R.id.btn_login);

    login.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            final Dialog dialog = new Dialog(getApplication());

            dialog.setContentView(R.layout.journey_details);
            dialog.setTitle("Android Custom Dialog Box");

            Button dialogButton = (Button) dialog.findViewById(R.id.btn_start_jrny);

            dialogButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });

            dialog.show();

        }
    });

它在 Log cat 中显示以下错误

     E/AndroidRuntime(1412): FATAL EXCEPTION: main
 E/AndroidRuntime(1412): Process: com.xont.geotracker, PID: 1412
 E/AndroidRuntime(1412): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
 E/AndroidRuntime(1412):    at android.view.ViewRootImpl.setView(ViewRootImpl.java:538)
 E/AndroidRuntime(1412):    at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:259)
 E/AndroidRuntime(1412):    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
 E/AndroidRuntime(1412):    at android.app.Dialog.show(Dialog.java:286)
 E/AndroidRuntime(1412):    at com.xont.geotracker.Loging$1.onClick(Loging.java:61)
 E/AndroidRuntime(1412):    at android.view.View.performClick(View.java:4424)
 E/AndroidRuntime(1412):    at android.view.View$PerformClick.run(View.java:18383)
 E/AndroidRuntime(1412):    at android.os.Handler.handleCallback(Handler.java:733)
 E/AndroidRuntime(1412):    at android.os.Handler.dispatchMessage(Handler.java:95)
 E/AndroidRuntime(1412):    at android.os.Looper.loop(Looper.java:137)
 E/AndroidRuntime(1412):    at android.app.ActivityThread.main(ActivityThread.java:4998)
 E/AndroidRuntime(1412):    at java.lang.reflect.Method.invokeNative(Native Method)
 E/AndroidRuntime(1412):    at java.lang.reflect.Method.invoke(Method.java:515)
 E/AndroidRuntime(1412):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
 E/AndroidRuntime(1412):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
 E/AndroidRuntime(1412):    at dalvik.system.NativeStart.main(Native Method)

有人可以帮我弄清楚错误。需要帮忙。谢谢!

1 个答案:

答案 0 :(得分:6)

变化

final Dialog dialog = new Dialog(getApplication());

final Dialog dialog = new Dialog(YourActivity.this);

如果您在Fragment内,请转到

final Dialog dialog = new Dialog(getActivity());

Dialog需要Context引用,其窗口标记不为空。这里ApplicationContext的窗口标记为空,而Activity将拥有它自己的窗口