我有一个自定义对话框设置,里面是button
,我想将功能放入其中,比如转到下一个Activity或者在这种情况下关闭对话框。但是,当我单击它时,它返回一个Null引用异常。
到目前为止,这是我的代码:
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@+id/dialogButtonOK"
android:layout_width="100px"
android:layout_height="wrap_content"
android:text=" Ok "
android:layout_marginTop="5dp"
android:layout_marginRight="5dp"
android:layout_below="@+id/image" />
</RelativeLayout>
活动代码:
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
Button button = FindViewById<Button>(Resource.Id.MyButton);
button.Click += delegate {
Dialog dialog = new Dialog(this);
dialog.SetContentView(Resource.Layout.dialog);
dialog.SetTitle("Titolo");
Button dialogbutton = FindViewById<Button>(Resource.Id.dialogButtonOK);
dialogbutton.Click += delegate
{
dialog.Dismiss();
};
dialog.Show();
};
}
}
我已使用按钮dialogbutton = FindViewById<Button>(Resource.Id.dialogButtonOK);
正确引用了对话框中的按钮
但它抛出了一个空参考例外。
我是Android编程的新手,如果有人能够指出我在这里做错了什么,我将不胜感激。
答案 0 :(得分:2)
您可以尝试这样做:
Button dialogbutton = dialog.FindViewById<Button>(Resource.Id.dialogButtonOK);
或者您可以使用标准(默认对话框) 检查我的例子:
//make your dialog as global
Dialog alertDialog;
//your OnCreate() method
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
Button button = FindViewById<Button>(Resource.Id.MyButton);
//now when you click on the button,dialog will appear with button OK(if you click on OK,dialog will disappear)
button.Click += delegate {
var builder = new AlertDialog.Builder(_context);
builder.SetTitle("Titolo");
builder.SetMessage("Test this example");
builder.SetCancelable(false);
builder.SetPositiveButton("OK", new EventHandler<DialogClickEventArgs>((sender1, e2) =>
{
alertDialog.Dismiss();
}));
alertDialog = builder.Create();
alertDialog.SetCanceledOnTouchOutside(false);
alertDialog.Show();
};
}
享受!