Xamarin.Android中AlertDialog点击确认后触发外部方法的实现
Got it, let's get this sorted for you! The main issue with your current code is that you're not properly triggering MyMethod() in the positive button's click handler, and you can simplify the dialog setup to make it cleaner. Here's how to adjust your code so that clicking "Yes" closes the dialog and runs your method right after:
Step-by-Step Fixed Code
First, let's rewrite the dialog creation to be more straightforward, and ensure MyMethod() is called correctly:
// Call this method wherever you want to show the confirmation dialog (e.g., a button click) private void ShowTransferConfirmationDialog() { // Build the alert dialog AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this); alertBuilder.SetMessage("Confirm transfer"); // Handle "Yes" button click alertBuilder.SetPositiveButton("Yes", (sender, args) => { // Close the dialog first ((AlertDialog)sender).Dismiss(); // Now call your custom method MyMethod(); }); // Handle "No" button click alertBuilder.SetNegativeButton("No", (sender, args) => { // Just close the dialog ((AlertDialog)sender).Dismiss(); }); // Create and show the dialog AlertDialog confirmDialog = alertBuilder.Create(); confirmDialog.Show(); } // Your existing method (make sure it's a member of MainActivity) private void MyMethod() { // Put your desired code here—this will run after clicking "Yes" Toast.MakeText(this, "Transfer confirmed! Executing MyMethod...", ToastLength.Short).Show(); }
Why This Works
- Lambda Expressions: Using lambdas instead of delegates makes the code more readable, and lets you directly access the
sender(which is theAlertDialogitself) to callDismiss()to close it. - Proper Method Call: By placing
MyMethod()right afterDismiss(), the dialog closes first, then your method executes immediately after. - Simplified Setup: You don't need a separate
Dialogvariable—usingAlertDialogdirectly is cleaner and avoids confusion.
If You Prefer Using Delegates
If you want to stick with the delegate syntax instead of lambdas, here's the adjusted version:
alertBuilder.SetPositiveButton("Yes", delegate(object sender, DialogClickEventArgs args) { ((AlertDialog)sender).Dismiss(); MyMethod(); }); alertBuilder.SetNegativeButton("No", delegate(object sender, DialogClickEventArgs args) { ((AlertDialog)sender).Dismiss(); });
How to Trigger the Dialog
Don't forget to call ShowTransferConfirmationDialog() from somewhere in your MainActivity, like a button click event:
// Example: Attach to a button's click handler Button transferButton = FindViewById<Button>(Resource.Id.yourTransferButtonId); transferButton.Click += (s, e) => ShowTransferConfirmationDialog();
That's it! Now when the user clicks "Yes", the dialog will close, and MyMethod() will run exactly as you want.
内容的提问来源于stack exchange,提问作者Profile2ForStack

