Xamarin Android 开关Xamarin.Android Switch

Switch 小组件(如下所示)允许用户在两个状态之间切换,例如打开或关闭。The Switch widget (shown below) allows a user to toggle between two states, such as ON or OFF. Switch 默认值为 OFF。The Switch default value is OFF. 此小组件的 "开" 和 "关" 状态如下所示:The widget is shown below in both its ON and OFF states:

切换小组件在关闭和打开状态中的屏幕快照Screenshots of a Switch widget in OFF and ON states

创建开关Creating a Switch

若要创建开关,只需在 XML 中声明一个 Switch 元素,如下所示:To create a switch, simply declare a Switch element in XML as follows:

<Switch android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

这将创建一个基本交换机,如下所示:This creates a basic switch as shown below:

显示处于关闭状态的开关的演示应用屏幕截图Screenshot of demo app displaying a Switch in the OFF state

更改默认值Changing Default Values

控件为开启和关闭状态显示的文本和默认值都是可配置的。Both the text that the control displays for the ON and OFF states and the default value are configurable. 例如,若要使开关默认为 ON,并读取 NO/YES 而不是 OFF/ON,可以设置以下 XML 中的 checkedtextOntextOff 属性。For example, to make the Switch default to ON and read NO/YES instead of OFF/ON, we can set the checked, textOn, and textOff attributes in the following XML.

<Switch android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"
        android:textOn="YES"
        android:textOff="NO" />

提供标题Providing a Title

Switch 小组件还支持通过设置 text 属性包括文本标签,如下所示:The Switch widget also supports including a text label by setting the text attribute as follows:

<Switch android:text="Is Xamarin.Android great?"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"
        android:textOn="YES"
        android:textOff="NO" />

此标记会在运行时生成以下屏幕截图:This markup produces the following screenshot at runtime:

在切换小组件之前水平文本的演示应用屏幕截图Screenshot of demo app with text horizontally preceding the Switch widget

Switch的值更改时,它将引发 CheckedChange 事件。When a Switch's value changes, it raises a CheckedChange event. 例如,在下面的代码中,我们将捕获此事件并显示一个 Toast 小组件,其中包含基于 isCheckedSwitch的消息,该消息作为 CompoundButton.CheckedChangeEventArg 参数的一部分传递到事件处理程序。For example, in the following code we capture this event and present a Toast widget with a message based upon the isChecked value of Switch, which is passed to the event handler as part of the CompoundButton.CheckedChangeEventArg argument.

Switch s = FindViewById<Switch> (Resource.Id.monitored_switch);
           
s.CheckedChange += delegate(object sender, CompoundButton.CheckedChangeEventArgs e) {
    var toast = Toast.MakeText (this, "Your answer is " +
        (e.IsChecked ?  "correct" : "incorrect"), ToastLength.Short);
    toast.Show ();
};