目录

Toggle

The Toggle component provides a clickable element in the check box, button, or switch type, typically used to switch between two states. For details, see Toggle.

Creating a Toggle

A toggle is created using ToggleOptions. The syntax is as follows:

Toggle(options: { type: ToggleType, isOn?: boolean })

In the preceding syntax, ToggleType indicates the toggle type, which can be Button, Checkbox, or Switch, and isOn indicates the state of the toggle.

Since API version 11, the default style of the Checkbox component is changed from rounded square to circle.

The API can be called in either of the following ways:

Setting Styles

Adding Events

The Toggle component supports the universal events. In addition, it can be bound to the onChange event so that it responds with custom behavior after being turned on or off.

Toggle({ type: ToggleType.Switch, isOn: false })
  .onChange((isOn: boolean) => {
    if(isOn) {
      // Operation
      // ···
    }
  })

Example Scenario

In this example, the Toggle component is used to enable or disable Bluetooth.

// xxx.ets
import { promptAction } from '@kit.ArkUI';

@Entry
@Component
export struct ToggleSample {
  @State message: string = 'off';
  pathStack: NavPathStack = new NavPathStack();

  build() {
    NavDestination() {
      Column({ space: 8 }) {
        Column({ space: 8 }) {
          Text('Bluetooth Mode: ' + this.message)
            .id('message')
          Row() {
            Text('Bluetooth')
            Blank()
            Toggle({ type: ToggleType.Switch })
              .id('toggle') // Replace the value of id with the actual ID.
              .onChange((isOn: boolean) => {
                if (isOn) {
                  this.message = 'on';
                  promptAction.openToast({ 'message': 'Bluetooth is on.' });
                } else {
                  this.message = 'off';
                  promptAction.openToast({ 'message': 'Bluetooth is off.' });
                }
              })
          }.width('100%')
        }
        .alignItems(HorizontalAlign.Start)
        .backgroundColor('#fff')
        .borderRadius(12)
        .padding(12)
        .width('100%')
      }
      .width('100%')
      .height('100%')
      .padding({ left: 12, right: 12 })
    }
    .backgroundColor('#f1f2f3')
    // Replace $r('app.string.ToggleCaseExample_title') with the actual resource file. In this example, the value in the resource file is "Bluetooth."
    .title($r('app.string.ToggleCaseExample_title'))
  }
}