关闭对话框,当按下OK按钮就可以了

本文关键字:OK 按钮 就可以 对话框 | 更新日期: 2023-09-27 18:16:00

如果用户点击一个按钮,出现一个对话框,要求输入一个字符串,在同一个对话框上有一个'OK'按钮,当用户按下它时,对话框应该关闭。这至少是计划,问题是:在将eventandler添加到OK按钮后,当用户打开对话框时,我的应用程序冻结了。

addNewFamButton = FindViewById<Button>(Resource.Id.newFamilyButton);
addNewFamButton.Click += (sender, e) => {
    Dialog dialog = new Dialog(this);
    dialog.SetContentView(Resource.Layout.addNewFamily);
    dialog.SetTitle("Add new family to the list");
    dialog.Show();
    // Problem starts here:
    Button saveNewFamily = FindViewById<Button>(Resource.Id.dialogButtonOK);
    saveNewFamily.Click += (object o, EventArgs ea) => { dialog.Dispose(); };                
};

我也用dialog.Cancel()试过,但我得到了相同的结果。如果我删除最后两行,对话框可以工作,但显然不会关闭。

修复:感谢user370305的简单解决方案:

Button saveNewFamily = dialog.FindViewById<Button>(Resource.Id.dialogButtonOK);

关闭对话框,当按下OK按钮就可以了

你的OK按钮是Dialog视图的一部分,所以你必须使用你的对话对象引用来找到那个视图,就像(我不熟悉xamarin但这个给你提示)

换行

// Problem starts here:
Button saveNewFamily = FindViewById<Button>(Resource.Id.dialogButtonOK);

Button saveNewFamily = dialog.FindViewById<Button>(Resource.Id.dialogButtonOK);

try this

        // create an EditText for the dialog
        final EditText enteredText = new EditText(this);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Title of the dialog");
        builder.setView(enteredText);
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int id)
            {
               // perform any operation you want
                enteredText.getText().toString());// get the text
              // other operations
                dialog.cancel();  // close the dialog
            }
        });
        builder.create().show();