使 Switch-Button(位于 AlertDialog 中)在状态更改时执行某些操作

Make Switch-Button (which is in an AlertDialog) do something when it's state changes

所以我想在 Activity 中创建一个小的弹出选项菜单。我已经有了显示菜单的代码

public void ShowOptionsDialog()
    {
        Android.Support.V7.App.AlertDialog.Builder optionDialog = new Android.Support.V7.App.AlertDialog.Builder(this);
        optionDialog.SetTitle("Optionen");            
        optionDialog.SetView(Resource.Layout.Options);
        optionDialog.Show();            
    }

Resource.Layout.Options 包含以下内容:

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center">
    <android.support.v7.widget.SwitchCompat
        android:id="@+id/previewSwitch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:checked="true"
        android:hint="Preview der Dokumente anzeigen"/>
</LinearLayout>

按下 Switch (on/off) 时,我该如何准确地告诉应用程序做某事?

您可以在 SwitchCompat 上设置事件处理程序并对用户所做的任何更改采取行动:

注意:v7 开关不包含 Android.Resource.Id.Custom,因此 FindViewById 中的 return 将为空,因此我们在这里创建自己的 FrameLayout:

protected void ShowOptionsDialog()
{
    Android.Support.V7.App.AlertDialog.Builder optionDialog = new Android.Support.V7.App.AlertDialog.Builder(this);
    optionDialog.SetTitle("Optionen");
    // Android.Resource.Id.Custom does not exist within v7 alertdialog 
    var frameLayout = new FrameLayout (optionDialog.Context);
    optionDialog.SetView(frameLayout);
    Android.Support.V7.App.AlertDialog alert = optionDialog.Create();
    var myView = alert.LayoutInflater.Inflate (Resource.Layout.Options, frameLayout);
    var mySwitch = myView.FindViewById<Android.Support.V7.Widget.SwitchCompat> (Resource.Id.previewSwitch); 
    mySwitch.CheckedChange += (object sender, CompoundButton.CheckedChangeEventArgs e) => {
        System.Diagnostics.Debug.WriteLine(e.IsChecked);
    };
    alert.Show ();
}

注意: Android 文档声明要执行以下操作以将自定义视图添加到您的 Switch,问题在于 SwitchCompat,该视图不存在。

 FrameLayout fl = (FrameLayout) findViewById(android.R.id.custom);
 fl.addView(myView, new LayoutParams(MATCH_PARENT, WRAP_CONTENT));

http://developer.android.com/reference/android/app/AlertDialog.html

您需要获得对您的交换机的引用。一种简单的方法是在代码中创建切换视图。这会将您的代码更改为类似的内容:

public void ShowOptionsDialog()
{
    var switchView = new Android.Support.V7.Widget.SwitchCompat(this);
    switchView.CheckedChange += (object sender, CompoundButton.CheckedChangeEventArgs e) => { //Do stuff depending on state };

    Android.Support.V7.App.AlertDialog.Builder optionDialog = new Android.Support.V7.App.AlertDialog.Builder(this);
    optionDialog.SetTitle("Optionen");            
    optionDialog.SetView(switchCompat);
    optionDialog.Show();            
}