2015-10-04 92 views
2

如果用戶單擊按鈕,會出現一個對話框,要求輸入一個字符串,並且在同一個對話框中有一個「確定」按鈕,當用戶按下該按鈕時,對話框應該關閉。這至少是計劃,問題是:將事件處理程序添加到「確定」按鈕後,當用戶打開對話框時,我的應用程序會凍結。關閉對話框,當按下確定按鈕時

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); 

回答

2

OK按鈕Dialog視圖的一部分,所以你必須使用你的對話對象的引用,類似的發現來看, (我不熟悉xamarin但是這一個給你提示)

更改線路,

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

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

這是我的尷尬問題的解決方案。 – hungariandude

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(); 
相關問題