如果用户点击某个按钮,会出现一个对话框,要求输入一个字符串,然后会出现“确定”字样。同一个对话框上的按钮,当用户按下该按钮时,该对话框应该关闭。这至少是计划,问题是:将事件处理程序添加到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);
答案 0 :(得分:2)
您的确定按钮是Dialog
视图的一部分,因此您必须使用对话框对象引用找到该视图,例如,(我不熟悉xamarin
但这个给你提示)
改变你的行,
// Problem starts here:
Button saveNewFamily = FindViewById<Button>(Resource.Id.dialogButtonOK);
带
Button saveNewFamily = dialog.FindViewById<Button>(Resource.Id.dialogButtonOK);
答案 1 :(得分:2)
试试这个
// 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();