我已经使用我自己的布局 xml 更新了警报对话框格式。
在这个定制的警报对话框中,有两个按钮,一个是保存正在输入的数据,另一个是取消按钮。
我怎么能写取消按钮,这样当用户点击它时,只是简单地关闭对话框?
public OnClickListener NewRowButtonListener = new OnClickListener()
{
@Override
public void onClick(View v)
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setView(getLayoutInflater().inflate(R.layout.custom_dialog_add, null));
builder.create();
AlertDialog Custom_dialog_add = builder.create();
Custom_dialog_add.show(); // show the Dialog
Button CancelButton = (Button) findViewById(R.id.CancelButton);
CancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {Custom_dialog_add.cancel();} //WRONG: Cannot refer to a non-final variable Custom_dialog_add inside an inner class defined in a different method
});
}
};
现在修改如下:
public OnClickListener NewRowButtonListener = new OnClickListener()
{
@Override
public void onClick(View v)
{
AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setView(getLayoutInflater().inflate(R.layout.custom_dialog_add, null));
dialog.create();
final AlertDialog test = dialog.create();
test.show();
Button close = (Button) findViewById(R.id.CancelButton);
close.setOnClickListener(new android.view.View.OnClickListener() {
public void onClick(View v) {
test.dismiss();
}
});
}
};
Eclipse 不会向修改后的编码报告错误,但在模拟时,它会运行空指针异常。logcat如下。这样的问题怎么解决?
09-28 20:15:19.505: E/AndroidRuntime(25847): FATAL EXCEPTION: main
09-28 20:15:19.505: E/AndroidRuntime(25847): java.lang.NullPointerException
09-28 20:15:19.505: E/AndroidRuntime(25847): at com.pearappx.gamescore3.MainActivity$4.onClick(MainActivity.java:422)
09-28 20:15:19.505: E/AndroidRuntime(25847): at android.view.View.performClick(View.java:3627)
09-28 20:15:19.505: E/AndroidRuntime(25847): at android.view.View$PerformClick.run(View.java:14329)
09-28 20:15:19.505: E/AndroidRuntime(25847): at android.os.Handler.handleCallback(Handler.java:605)
09-28 20:15:19.505: E/AndroidRuntime(25847): at android.os.Handler.dispatchMessage(Handler.java:92)
09-28 20:15:19.505: E/AndroidRuntime(25847): at android.os.Looper.loop(Looper.java:137)
09-28 20:15:19.505: E/AndroidRuntime(25847): at android.app.ActivityThread.main(ActivityThread.java:4511)
09-28 20:15:19.505: E/AndroidRuntime(25847): at java.lang.reflect.Method.invokeNative(Native Method)
09-28 20:15:19.505: E/AndroidRuntime(25847): at java.lang.reflect.Method.invoke(Method.java:511)
09-28 20:15:19.505: E/AndroidRuntime(25847): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
09-28 20:15:19.505: E/AndroidRuntime(25847): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
09-28 20:15:19.505: E/AndroidRuntime(25847): at dalvik.system.NativeStart.main(Native Method)