0

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

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

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();
}

日志猫:

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)
4

1 回答 1

2

改变

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

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

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

希望能帮助到你。

于 2014-01-01T16:08:38.823 回答