按钮单击对话框中的错误

时间:2013-10-08 07:31:21

标签: android dialog

在我的应用程序中,我使用一个对话框来加载布局本身。

当我点击对话框中的按钮(对话框中已加载的布局中的按钮)时,我的应用程序崩溃并显示消息不幸的是应用已停止。代码的关键部分如下。

void contact_list_dialog()
{
   dialog = new Dialog(MainActivity.this,
                android.R.style.Theme_Translucent);
   dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

   dialog.setContentView(R.layout.test);

   b1=(Button)findViewById(R.id.button1);
   b1.setOnClickListener(this);

   dialog.setCancelable(true);
   dialog.setTitle("ListView");

   dialog.getWindow().setGravity(Gravity.RIGHT);
   dialog.getWindow().setLayout(300, 500);

   dialog.show();
}

Logcat:

01-01 15:34:46.700: E/AndroidRuntime(13044): FATAL EXCEPTION: main

01-01 15:34:46.700: E/AndroidRuntime(13044): java.lang.NullPointerException
01-01 15:34:46.700: E/AndroidRuntime(13044):    at com.sms.card.offline.MainActivity.contact_list_dialog(MainActivity.java:184)
01-01 15:34:46.700: E/AndroidRuntime(13044):    at com.sms.card.offline.MainActivity.onClick(MainActivity.java:304)
01-01 15:34:46.700: E/AndroidRuntime(13044):    at android.view.View.performClick(View.java:4204)
01-01 15:34:46.700: E/AndroidRuntime(13044):    at android.view.View$PerformClick.run(View.java:17355)
01-01 15:34:46.700: E/AndroidRuntime(13044):    at android.os.Handler.handleCallback(Handler.java:725)
01-01 15:34:46.700: E/AndroidRuntime(13044):    at android.os.Handler.dispatchMessage(Handler.java:92)
01-01 15:34:46.700: E/AndroidRuntime(13044):    at android.os.Looper.loop(Looper.java:137)
01-01 15:34:46.700: E/AndroidRuntime(13044):    at android.app.ActivityThread.main(ActivityThread.java:5041)
01-01 15:34:46.700: E/AndroidRuntime(13044):    at java.lang.reflect.Method.invokeNative(Native Method)
01-01 15:34:46.700: E/AndroidRuntime(13044):    at java.lang.reflect.Method.invoke(Method.java:511)
01-01 15:34:46.700: E/AndroidRuntime(13044):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-01 15:34:46.700: E/AndroidRuntime(13044):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)  
01-01 15:34:46.700: E/AndroidRuntime(13044):    at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:2)

更改

b1=(Button)findViewById(R.id.button1);

b1=(Button)dialog.findViewById(R.id.button1);

您没有正确地获得按钮。这会给你NullPointerException。您应该使用dialog.来初始化对话框的视图。

希望它有所帮助。