Make Switch-Button(在AlertDialog中)在状态发生变化时执行某些操作

时间:2016-04-26 14:36:15

标签: android xamarin alertdialog android-appcompat

所以我想在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>

当按下开关时(开/关),我该如何告诉应用程序做某事?

2 个答案:

答案 0 :(得分:2)

您可以在SwitchCompat上设置事件处理程序,并根据用户所做的任何更改执行操作:

注意:v7开关不包含Android.Resource.Id.Custom,因此将从FindViewById返回null,因此我们在这里创建自己的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 ();
}

enter image description here

注意: 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

答案 1 :(得分:-1)

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

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