在本节中,我们将创建一个按钮,单击该按钮会显示警告对话框.该对话框包含两个按钮,即删除和取消按钮.
首先,转到 main. axml 并在线性布局中创建一个新按钮,如下面的代码所示.
<?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:orientation = "vertical" android:layout_width = "fill_parent" android:background = "#d3d3d3" android:layout_height = "fill_parent"> <Button android:id="@+id/MyButton" android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:text = "Click to Delete" android:textColor = "@android:color/background_dark" android:background = "@android:color/holo_green_dark" /> </LinearLayout>
接下来,打开 MainActivity.cs 以创建警告对话框并添加其功能.
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Main); Button button = FindViewById<Button>(Resource.Id.MyButton); button.Click += delegate { AlertDialog.Builder alertDiag = new AlertDialog.Builder(this); alertDiag.SetTitle("Confirm delete"); alertDiag.SetMessage("Once deleted the move cannot be undone"); alertDiag.SetPositiveButton("Delete", (senderAlert, args) => { Toast.MakeText(this, "Deleted", ToastLength.Short).Show(); }); alertDiag.SetNegativeButton("Cancel", (senderAlert, args) => { alertDiag.Dispose(); }); Dialog diag = alertDiag.Create(); diag.Show(); }; }
完成后,构建并运行您的应用程序以查看结果.
在上面的代码中,我们创建了一个名为alertDiag的警告对话框,其中包含以下两个按钮 :
setPositiveButton : 它包含删除按钮操作,点击后会显示确认消息已删除.
setNegativeButton : 它包含一个取消按钮,单击该按钮只会关闭警告对话框.