【问题标题】:Xamarin Android - custom alert dialog with checkboxes, exception thrownXamarin Android - 带有复选框的自定义警报对话框,引发异常
【发布时间】:2015-04-04 07:07:21
【问题描述】:

我有一个弹出的警报对话框,并通过复选框为用户提供多个选择,以及供用户输入一些文本的编辑文本。自定义警报对话框从布局膨胀,到目前为止一切都很好。

我的问题是尝试处理复选框的点击事件。我不断收到空引用异常,我无法弄清楚我哪里出错了。我尝试过以各种方式编写代码,但我认为我现在对这个问题视而不见。

我需要查看复选框是否被选中并将结果分配给我的布尔值。

在我尝试处理点击事件时抛出异常。任何帮助表示赞赏,谢谢。

var myCustomAlert = LayoutInflater.Inflate(Resource.Layout.delegateCaptureAlertLayout, null);

bool wantphoneCall = true;
bool wantBrochure = false;
bool wantMailingList = false;
string additionalText; 

AlertDialog.Builder builder;
builder = new AlertDialog.Builder(this);
builder.SetTitle("Your request");
builder.SetView(myCustomAlert);
builder.SetMessage("Some message");
builder.SetPositiveButton("OK", delegate { // do something 
    });
builder.Show ();


CheckBox checkCallMe = FindViewById<CheckBox> (Resource.Id.checkBoxCallMe);
CheckBox checkBrochure = FindViewById<CheckBox> (Resource.Id.checkBoxBrochure);
CheckBox checkMailingList = FindViewById<CheckBox> (Resource.Id.checkBoxMailing);
EditText additionalInfoText = FindViewById<EditText> (Resource.Id.textAdditionalInfo);

  checkCallMe.Click += (sender, e) => {             // exception thrown here
            Console.WriteLine("Checkbox is clicked");

            if (checkCallMe.Checked)
            {
                wantphoneCall = true;
                Console.WriteLine("Checkbox is checked");
            }
            else
            {
                wantphoneCall = false;
                Console.WriteLine("Checkbox is not checked");
            }

【问题讨论】:

    标签: android checkbox xamarin android-alertdialog nullreferenceexception


    【解决方案1】:

    您调用FindViewById() 的方式导致它在您的活动布局中搜索 CheckBox 对象,但它们存在于对话框中,不会被搜索。如果您在该部分设置断点,您会发现您的 CheckBox 对象都是null,因此尝试附加事件处理程序时会出现异常。

    改为在对话框的膨胀视图上调用 FindViewById()

    CheckBox checkCallMe = myCustomAlert.FindViewById<CheckBox> (Resource.Id.checkBoxCallMe);
    

    【讨论】:

    • 非常感谢。节省了我很多时间和痛苦!
    猜你喜欢
    • 2021-11-10
    • 2015-04-13
    • 2016-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多