目录

Accessibility Development

Overview

Accessibility is a system-level framework designed to ensure that everyone can access and use information equally and conveniently under any circumstances. Specifically, the ScreenReader function provided for visually impaired users converts visible information into spoken words, empowering them to easily navigate and interact with their devices.

ScreenReader

ScreenReader empowers visually impaired users operate devices without needing to look at the screen. After ScreenReader is enabled, users can use accessibility gestures to move the focus, and the device will announce its details in real time.

[h2]Functions

[h2]Highlights

  1. Wider user coverage: Applications adapted to ScreenReader can accurately reach millions of visually impaired users who rely on assistive technologies, breaking down digital barriers and making products accessible to more users.
  2. Compliance with regulations and design standards: Adapting to ScreenReader is a core measure to comply with global accessibility design standards. It not only meets the digital inclusion regulations of various countries/regions, but also aligns with the modern product design concept of "accessible to all."
  3. Social responsibilities fulfillment and brand value enhancement: Adapting to ScreenReader is a concrete action to promote digital equity, demonstrate the brand's responsibility to respect all users and help build an accessibility environment, and improve brand awareness.
  4. Enhanced user experience for visually impaired users: During the adaptation process, focus heavily on core usability enhancements by embedding explicit descriptions, streamlined action hints, and proper focus target framing to guarantee a fluid and dignified digital experience for visually impaired users.
  5. Lightweight adaptation does not affect core experience: Adapting to ScreenReader does not require changes to the core logic or UI design of the application. While implementing accessibility support, the innovative features and visual style of the product are fully retained.

[h2]ScreenReader Operation Guide

ScreenReader can be enabled using any of the following methods:

After ScreenReader is enabled, common gestures are converted into accessibility gestures. Accessibility gestures can be customized by going to Settings > Accessibility > ScreenReader > More settings > Custom gestures. The default gestures and their corresponding actions are as follows.

Table 1 Accessibility gestures and corresponding actions

Gesture Action
Single-finger tap Focus on an element and read aloud its information. For example, tapping the Settings icon with one finger moves the focus to it and triggers the voice broadcast "Settings. Double-tap to open..."
Single-finger swipe (up/down/left/right) Move the focus to an adjacent element.
Single-finger double-tap Trigger a click action on the focused element. Once the target element is focused, double-tapping anywhere on the screen executes the click action. For example, double-tapping the focused Settings icon opens the Settings screen.
Single-finger double-tap and hold Activate the standard long-press gesture for the focused element. After focusing on the target, double-tapping and holding anywhere on the screen triggers its long-press gesture. For example, long-pressing an application icon pops up its shortcut menu.
Two-finger swipe Scroll through lists or trigger the system back function.

[h2]ScreenReader Focus Principles

  1. Navigation sequence: The focus navigation must strictly follow the visual layout sequence of the interface, moving sequentially from top to bottom and left to right.
  2. Focus scope: Only visible components on the screen can be focused through touch or swipe gestures. Hidden content is not included in the focus scope.
  3. Number of focus points: There must be one, and only one, active accessibility focus on the visible screen at any given time.
  4. Focus target size: The dimensions of the focus target must be optimized. Avoid excessively small targets that hinder touch perception, or overly large targets that overlap adjacent accessibility nodes and trigger focus loss.
  5. Default focus: When a new application screen, a new screen within the same application, or a new pop-up window appears, the focus automatically moves to the first element on the screen.

The preceding focus principles can be implemented through accessibility APIs.

Table 2 Focus control and corresponding APIs

Function Implementation
Navigation order control Customize the focus navigation logic using accessibilityNextFocusId to specify the next component to receive focus during focus switching.
Focus scope control

- For hidden/non-interactive content, use accessibilityLevel('no') to prevent it from being focused.

- For interactive areas without actual nodes, use accessibilityVirtualNode to configure a virtual node as the focus placeholder.

Single active focus assurance Ensure that one, and only one, active focus exists within the visible area of the screen. Use sendAccessibilityEvent('requestFocusForAccessibility') to automatically assign the default focus when no active focus is detected.
Focus target size

- Insufficient focus target: For semantically coherent parent components with larger operational bounds, you are advised to wrap them into a unified focus unit using accessibilityGroup.

- Excessive focus target: You are advised to calibrate the focusable bounds of UI components to eliminate overlap with adjacent accessibility nodes and prevent unintended node occlusion.

[h2]ScreenReader Announcement Principles

When an element is selected, ScreenReader announces the content in the following sequence: component status → text content → component type → action hints. The system will only announce attributes that actively exist.

All the preceding four types of announcement elements support content customization. If you need to modify the spoken text for a specific type of attributes, you can configure it by referring to the custom API corresponding to the attribute. For details, see Table 3.

Table 3 Basic announcement content when a component is selected

Announcement Content Configuration Method
Component status Use accessibilityChecked and accessibilitySelected to configure the spoken text for the component status, for example, "Selected" or "Deselected".
Text content Use accessibilityText to configure the spoken text for the core text of a component, such as "Home" and "Settings".
Component type Use accessibilityRole to declare the component type, such as "Button" and "Edit box".
Action hints Use accessibilityDescription to define the operation guide of a component, for example, "Double-tap with one finger to play."

When the focus remains unchanged but the announcement content requires real-time updates (for example, dynamic data changes), you can implement this by calling the sendAccessibilityEvent('announceForAccessibility') API. This API is applicable to scenarios where the content changes dynamically, and the announcement needs to reflect changes, such as "Downloaded 50%." Example:

Accessibility Attributes Development Guide

Accessibility attributes allow you to customize the accessibility announcement text for the status, text content, component type, and action hint of custom components. This enables precise control over ScreenReader announcements, ultimately delivering a better user experience in accessibility scenarios.

Function Description
Customizing announcement content Customize the accessibility spoken text for component status, descriptions, type, and action hint to gain precise control over ScreenReader outputs.
Customizing focus Define custom focus groups, component focusability, and focus navigation order.
Setting the scrollable mode Set the scrollable mode.
Setting the accessibility focus drawing level Set the drawing level for the accessibility focus.

[h2]Setting the Accessibility Text

accessibilityText is a dedicated attribute used to configure the core accessibility text content for a component. Its main purpose is to convey the key information of the component. You are advised to keep the configured text be concise, accurate, and semantically complete.

When setting the accessibility text, adhere to the following principles:

The following provides two examples to demonstrate how to supplement core accessibility spoken text for a button without default text by configuring accessibilityText.

To experience the expected behavior when running these examples, you need to enable ScreenReader on the device in advance. Otherwise, no audible effect will be produced.

Example 1: For a button without default text, ScreenReader announces "Button. Double-tap with one finger to execute." Users cannot understand the function (play) of the button through the announcement.

@Entry
@Component
export struct AccessibilityTextCase01 {
  build() {
    // ...
    Column() {
        Button()
        .onClick(() => {
            // Core logic for playing audio and video.
        })
    }
    // ...
  }
}

Example 2: Building on example 1, after adding the accessibilityText attribute, ScreenReader announces "Play. Button. Double-tap with one finger to execute." Users can now understand the function of the button through the announcement.

@Entry
@Component
export struct AccessibilityTextCase02 {
  build() {
    // ...
      Column() {
        // Ensure that the icon exists in the resource/base/media directory. You can replace the icon with an appropriate one.
        Button()
          .onClick(() => {
            // Core logic for playing audio and video.
          })
          .accessibilityText('Play') // Configure the core accessibility text.
      }
    // ...
  }
}

[h2]Setting Accessibility Description

accessibilityDescription is used to provide action hints for components, helping users understand the exact actions that will be executed. For example, it is used in scenarios where the system's default usage hints fail to convey the specific context of the interaction. This information is announced after the text content. If the current control has a default usage hint (for example, for a component that can be tapped, the default usage hint is "Double-tap with one finger to execute"), the accessibility description will replace the system's usage hint, that is, only the accessibility description will be announced.

After the usage hint of ScreenReader is disabled, the accessibility description will not be announced.

The following provides two examples to illustrate how to set the accessibility description for a Button component.

To experience the expected behavior when running these examples, you need to enable ScreenReader on the device in advance. Otherwise, no audible effect will be produced.

Example 1: When a Button component is used as the full-screen button for video playback, focusing on this button causes ScreenReader to only announce "Button. Double-tap with one finger to activate." Users cannot discern the specific meaning of this operation.

@Entry
@Component
export struct AccessibilityDescriptionCase01 {
  build() {
    // ...
    Button()
      .background(Color.Blue)
      .onClick(() => {
        // Full-screen logic.
      })
    // ...
  }
}

Example 2: Building on example 1, after adding accessibilityDescription, focusing on the button causes ScreenReader to announce "Button. Double-tap to display in full screen." Users can now clearly understand the intended operation.

@Entry
@Component
export struct AccessibilityDescriptionCase02 {
  build() {
    // ...
    Button()
      .background(Color.Blue)
      .onClick(() => {
        // Full-screen logic.
      })
      // Custom hint for the operation.
      .accessibilityDescription('Double-tap with one finger to display in full screen') // Custom hint for the operation.
    // ...
  }
}

[h2]Setting the Type of an Accessibility Component

accessibilityRole is used to set the accessibility role type for a custom component, helping users understand the type of the component being operated. For example, when using basic components like Column or Row to build a custom tappable component, if you want the component to be announced by ScreenReader as "Button", you can set accessibilityRole to BUTTON.

The following two examples contrast and demonstrate how to customize the accessibility role type for a custom component.

To experience the expected behavior when running these examples, you need to enable ScreenReader on the device in advance. Otherwise, no audible effect will be produced.

Example 1: In this example, the Column component is used. Since the Column component is not a standard button component, ScreenReader will only read out the text content "Like".

@Entry
@Component
export struct AccessibilityRoleCase01 {
  build() {
    // ...
    Column() {
      Text ('Like')
    }
    .onClick(() => {
      // Service logic.
    })
    // ...
  }
}

Example 2: Based on example 1, set the accessibilityRole attribute of the Column component to BUTTON (announcing "button"). The final content announced by ScreenReader is "Like. Button. Double-tap with one finger to execute."

@Entry
@Component
export struct AccessibilityRoleCase02 {
  build() {
    // ...
    Column() {
      Text ('Like')
    }
    .onClick(() => {
      // Service logic.
    })
    .accessibilityRole(AccessibilityRoleType.BUTTON)
    // ...
  }
}

[h2]Setting Whether an Accessibility Node Is Selected

accessibilityChecked and accessibilitySelected are two attributes used to enhance accessibility experience. They are mainly used to convey the selection status of a component to ScreenReader.

Setting selection state for multi-select scenarios

The accessibilityChecked attribute is used to indicate whether a component (for example, two-state or three-state component like check box or toggle button) is selected in multi-select scenarios. It applies to scenarios requiring clear "selected/unselected" semantics and supports the following values:

The following provides two examples to demonstrate how different values of accessibilityChecked are announced.

To experience the expected behavior when running these examples, you need to enable ScreenReader on the device in advance. Otherwise, no audible effect will be produced.

Example 1: The following uses the Text component as an example. When accessibilityChecked is set to true, the current component is in selected state. When the focus is on "Option 1", the announcement "Selected. Option 1" is played.

@Entry
@Component
export struct AccessibilityCheckedCase01 {
  build() {
    // ...
    Column() {
      Text('Option 1');
        .accessibilityChecked(true)
    }
    // ...
  }
}

Example 2: The following uses the Text component as an example. When accessibilityChecked is set to false, the current component is in unselected state. When the focus is on "Option 1", the announcement "Unselected. Option 1" is played.

@Entry
@Component
export struct AccessibilityCheckedCase02 {
  build() {
    // ...
    Column() {
      Text('Option 1');
        .accessibilityChecked(false)
    }
    // ...
  }
}

Setting selection state for single-select scenarios

The accessibilitySelected attribute is used to indicate whether a component (for example, a single-select list or tab) is selected in single-select scenarios. It applies to scenarios requiring differentiation of "current selected items" (for example, single-select groups and navigation menus) and supports the following values:

The following provides two examples to demonstrate how different values of accessibilitySelected are announced.

To experience the expected behavior when running these examples, you need to enable ScreenReader on the device in advance. Otherwise, no audible effect will be produced.

Example 1: The following uses the Text component as an example. When accessibilitySelected is set to true, the current component is in the selected state. When the focus is on "Option 1", the announcement "Selected. Option 1" is played.

@Entry
@Component
export struct AccessibilitySelectedCase01 {
  build() {
    // ...
    Column() {
      Text('Option 1');
        .accessibilitySelected(true)
    }
    // ...
  }
}

Example 2: The following uses the Text component as an example. When accessibilitySelected is set to false, the current component is in unselected state. When the focus is on "Option 1", the announcement "Unselected. Option 1" is played.

@Entry
@Component
export struct AccessibilitySelectedCase02 {
  build() {
    // ...
    Column() {
      Text('Option 1');
        .accessibilitySelected(false)
    }
    // ...
  }
}

In ArkUI accessibility attributes, both accessibilityChecked and accessibilitySelected are used to indicate the state of a component, but they have fundamentally different application scenarios and semantic meanings. The following table provides a comparison of these two.

Table 4 Comparison between accessibilityChecked and accessibilitySelected

Attribute accessibilityChecked accessibilitySelected
Scenario Binary or ternary components, such as check boxes and toggles. Mutually exclusive selection scenarios, such as single-select lists and tabs.
Semantic objectives Physical state of components (for example, whether a switch is on). Navigation focus item (for example, current selected item in a list).
State persistence Usually requires explicit saving (such as form submission). Temporary (changes with focus navigation).
Typical components Checkbox and Toggle. List and Tabs.
Announcement content true: selected; false: unselected. true: selected; false: not announced.

[h2]Setting Accessibility Groups

The accessibilityGroup attribute is used to configure whether to enable the accessibility grouping function for a component. If this feature is enabled, the component and all its child components are treated as a single accessibility node, and accessibility services no longer identify or process the child components individually. The attribute supports the following values:

The following two examples compare the effects of accessibility grouping in the Column component.

To experience the expected behavior when running these examples, you need to enable ScreenReader on the device in advance. Otherwise, no audible effect will be produced.

Example 1: In this scenario, there are three Text child components that can be focused separately. Users cannot perceive the complete time information coherently and need to focus on each component multiple times to obtain the full content.

@Entry
@Component
export struct AccessibilityGroupCase01 {
  build() {
    // ...
    Column() {
      Text ('2026')
      Text('Jan. 27')
      Text ('Tuesday')
    }
    // ...
  }
}

Example 2: After accessibilityGroup is enabled for the Column component based on example 1, only the Column component can be focused. All Text components under the Column component are concatenated into "Tuesday, January 27, 2026" for announcement, and a single Text component cannot be focused separately.

@Entry
@Component
export struct AccessibilityGroupCase02 {
  build() {
    // ...
    Column() {
      Text ('2026')
      Text('Jan. 27')
      Text ('Tuesday')
    }
    .accessibilityGroup(true)
    // ...
  }
}

[h2]Setting the Accessibility Level

accessibilityLevel is used to identify the accessibility level of a component. It controls whether the component can be identified by the accessibility service. The following values are supported:

In this example, the Text component is used. After Text.accessibilityLevel('yes') is set for the component, it can be recognized by ScreenReader. If this attribute is not set, the Text component corresponding to "Text 1" cannot be focused independently.

To experience the expected behavior when running these examples, you need to enable ScreenReader on the device in advance. Otherwise, no audible effect will be produced.

@Entry
@Component
export struct AccessibilityLevelCase01 {
  build() {
    // ...
    Column() {
      Text('HelloWorld').fontSize(50).fontWeight(FontWeight.Bold)
    }
    .accessibilityGroup(true)
    .accessibilityLevel('yes')
    // ...
  }
}

[h2]Setting Accessibility Virtual Nodes

The accessibilityVirtualNode attribute is used to add a virtual accessibility node for a self-drawing component that cannot be identified as an accessibility node by the system. In this way, ScreenReader can focus on and read the information about the node.

In this example, Text('text 1') under the Column component simulates a custom component that cannot be identified by the system. After accessibilityVirtualNode is set for the Column component, Text('Text 2') will occupy the position of Text('Text 1') as an accessibility node. In this way, ScreenReader can focus on Text('Text 2') and read it aloud.

To experience the expected behavior when running these examples, you need to enable ScreenReader on the device in advance. Otherwise, no audible effect will be produced.

@Entry
@Component
struct VirtualNodeExample {
  @Builder customAccessibilityNode() {
    Text('Text 2')
      .fontSize(50)
      .fontWeight(FontWeight.Bold)
  }

  build() {
    Column() {
      Text('Text 1')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
    }
    .accessibilityVirtualNode(this.customAccessibilityNode)
  }
}

[h2]Setting the Next Focus for Accessibility

The accessibilityNextFocusId attribute specifies the ID of the next component to receive focus during focus navigation. It is recommended that you set the focus sequence from top to bottom and left to right. If the actual focus navigation order is inconsistent with the visual display order, you can use this attribute to adjust the focus sequence of nodes.

The following two examples contrast and demonstrate how to change the focus navigation order.

To experience the expected behavior when running these examples, you need to enable ScreenReader on the device in advance. Otherwise, no audible effect will be produced.

Example 1: In this example, the visual presentation sequence of the components is "A -> C -> B -> D". The focus navigation order is the same as the visual order, which is also "A -> C -> B -> D".

@Entry
@Component
export struct AccessibilityNextFocusIdCase01 {
  build() {
    // ...
    Column() {
      Button('A')
      Button('C')
      Button('B')
      Button('D')
    }
    // ...
  }
}

Example 2: Based on example 1, use the accessibilityNextFocusId attribute to customize the focus navigation order to "A -> B -> C -> D."

@Entry
@Component
export struct AccessibilityNextFocusIdCase02 {
  build() {
    // ...
    Column() {
      Button('A')
        .accessibilityNextFocusId('b')
      Button('C')
        .id('c')
        .accessibilityNextFocusId('d')
      Button('B')
        .id('b')
        .accessibilityNextFocusId('c')
      Button('D')
        .id('d')
    }
    // ...
  }
}
  • Avoid trapping focus navigation in an infinite loop. For example, if you set accessibilityNextFocusId to B for component A and to A for component B, the focus navigation order will change to A→B→A→B... and eventually enter an infinite loop. This situation must be avoided when adapting to the accessibility feature.
  • Unless necessary, avoid situations where a node cannot be traversed by the focus. For example, if the component tree contains components A, B, C, D, and E, the default focus navigation order is A→B→C→D→E. If accessibilityNextFocusId is set to D only for B, the focus navigation order changes to A→B→D→E→A→B→D→E..., which causes node C to never be traversed by the focus.
  • To specify the current node as the tail node of the page, you can configure the next node of the current node to itself. For example, set accessibilityNextFocusId to A for A. When focused on this node, the first downward focus navigation triggers the end-of-page sound effect; a subsequent downward navigation moves focus to the page's initial focus node.

[h2]Setting the Scrollable Mode

accessibilityScrollTriggerable is used to set whether the accessibility component supports scroll-triggered operations. When a user triggers focus navigation by swiping the screen, ScreenReader will automatically initiate a scroll operation if there are no focusable components available within the currently visible area of the container.

The following two examples contrast and demonstrate how to configure the accessibilityScrollTriggerable property to control the scrolling behavior in accessibility mode.

To experience the expected behavior when running these examples, you need to enable ScreenReader on the device in advance. Otherwise, no audible effect will be produced.

Example 1: The following uses the List component as an example. When the focus is on the last node in the visible range of the list, for example, item 5, triggering further downward focus navigation will initiate an automatic scroll of the list, and the focus will move to item 6, a content node that is originally invisible.

@Entry
@Component
export struct AccessibilityScrollTriggerableCase01 {
  private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

  build() {
    // ...
    Column() {
      List({ space: 20, initialIndex: 0 }) {
        ForEach(this.arr, (item: number) => {
          ListItem() {
            Text (`Item ${item}`)
              .width('100%')
              .height(100)
              .textAlign(TextAlign.Center)
          }
        }, (item: string) => item)
      }
    }
    .width('100%')
    .height('100%')
    // ...
  }
}

Example 2: Based on example 1, after accessibilityScrollTriggerable(false) is configured for the List component, triggering further downward focus navigation will no longer initiate an automatic scroll of the list when the focus is on the last node within the visible area, such as item 5. If downward focus navigation is triggered again, the focus will wrap around to the first focusable node on the page.

@Entry
@Component
export struct AccessibilityScrollTriggerableCase02 {
  private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

  build() {
    // ...
    Column() {
      List({ space: 20, initialIndex: 0 }) {
        ForEach(this.arr, (item: number) => {
          ListItem() {
            Text (`Item ${item}`)
              .width('100%')
              .height(100)
              .textAlign(TextAlign.Center)
          }
        }, (item: string) => item)
      }
      .accessibilityScrollTriggerable(false)
    }
    .width('100%')
    .height('100%')
    // ...
  }
}

[h2]Setting the Accessibility Focus Drawing Level

The accessibilityFocusDrawLevel attribute is used to set the drawing level of the green accessibility focus border. When the green border indicating the focus is obscured or covered by a layer with a higher Z-order, configuring this attribute can elevate its drawing Z-order, ensuring that the green border is clearly displayed.

The following two examples provide a comparison to demonstrate how to elevate the Z-order of the green accessibility focus border by configuring accessibilityFocusDrawLevel.

To experience the expected behavior when running these examples, you need to enable ScreenReader on the device in advance. Otherwise, no audible effect will be produced.

Example 1: The green focus border of the Text 1 button is partially obscured and clipped by the Text 2 button, preventing it from being fully displayed.

@Entry
@Component
export struct AccessibilityFocusDrawLevelCase01 {
  build() {
    // ...
    Stack() {
      Button('Text 1')

      Button('Text 2')
        .accessibilityLevel('no')
    }
    // ...
  }
}

Example 2: Based on example 1, after accessibilityFocusDrawLevel(FocusDrawLevel.TOP) is configured for the Text 1 button, the green focus border of the button can be completely displayed.

@Entry
@Component
export struct AccessibilityFocusDrawLevelCase02 {
  build() {
    // ...
    Stack() {
      Button('Text 1')
        .accessibilityFocusDrawLevel(FocusDrawLevel.TOP)

      Button('Text 2')
        .accessibilityLevel('no')
    }
    // ...
  }
}

[h2]Setting Custom Accessibility Operations

accessibilityCustomActions is used to set custom accessibility operations for a component. You can set an array of custom actions to bind custom operation callbacks to the component based on the operation name.

If the operation name of a component contains IncreaseValue or DecreaseValue, other custom operations of the component are ignored. Instead, a single-finger swipe up or down is supported to trigger the service callback to adjust the value

The following provides two examples to describe how to configure the accessibilityCustomActions property to customize operations and customizations for accessibility focus, and how to configure and implement single-finger swiping up or down to adjust the value.

To experience the expected behavior when running these examples, you need to enable ScreenReader on the device in advance. Otherwise, no audible effect will be produced.

Example 1:

@Entry
@Component
struct MailItem {
  @State private mailTitle: string = 'Important Notice'
  @State private mailContent: string = 'This is an important email.'
  @State private isRead: boolean = false;

  build() {
    Column() {
    Text(this.mailTitle)
      .fontSize(18)
      .fontWeight(FontWeight.Bold)
    Text(this.mailContent)
      .fontSize(14)
      .margin({ top: 8 })
    }
    .padding(16)
    .backgroundColor(this.isRead ? Color.Gray : Color.White)
    .accessibilityCustomActions([
      {
        name: 'Mark as read',
        onAction: () => {
          this.isRead = true;
          // Implement the logic for marking an email as read.
        }
      },
      {
        name: 'Delete',
        onAction: () => {
          // Perform the delete operation.
        }
      }
    ])
  }
}

Example 2 (supporting single-finger swiping up and down for adjustment.):

@Entry
@Component
struct MailItem {
    @State private value: number = 70;
    private gradientColor: LinearGradient = new LinearGradient([
        { color: "#87BDF9", offset: 0.5 },
        { color: "#3662F0", offset: 1.0 }
    ])

    build() {
        Colomn({ space: 15 }) {
            Text('Linear: ')
                .fontSize(9)
                .fontColor(0XCCCCCC)
                .width('90%')
            Progress({
                value: this.value,
                total: 100,
                type: ProgressType.Linear
            })
            .width(100)
            .style({ strokeWidth: 20})
            .color(this.gradientColor)
            .accessibilityCustomActions([
                {
                    name: 'IncreaseValue',
                    onAction: () => {
                        this.value += 10;
                        // Implement other service capabilities.
                    }
                },
                {
                    name: 'DecreaseValue',
                    onAction: () => {
                        this.value -= 10;
                        // Implement other service capabilities.
                    }
                }
            ])
        }
    }
}

Accessibility Method Development Guide

Accessibility methods primarily provide you with two types of core capabilities, mainly including accessibility action callbacks provided by ArkUI components and status query method provided by accessibility services.

The effects of all examples in this document must be verified after the ScreenReader is enabled.

Table 5 Main functions of accessibility methods

Function Method/Attribute Description
Accessibility focus status callback onAccessibilityFocus Listens for the component's accessibility focus status changes.
Accessibility touch event callback onAccessibilityHover Listens for single-finger touch (hover) actions, which are triggered in ScreenReader mode.
Accessibility click event callback onAccessibilityActionIntercept Intercepts and consumes accessibility click actions.
Touch guide status check on/off touchGuideStateChange Listens for status change events of the touch guide function being enabled or disabled.
Active focusing sendAccessibilityEvent('requestFocusForAccessibility') Triggers active focusing.
Active announcement accessibility.sendAccessibilityEvent('announceForAccessibility') Triggers active announcement of the focus.

[h2]Accessibility Focus Status Callback

The onAccessibilityFocus method is a callback used to listen for the accessibility focus status of a component. When the accessibility focus status of the component changes, this callback is triggered.

In this example, the Button component is used. When the focus is on the Text component, the Button component displays Unfocused. When the focus is on the Button component, the onAccessibilityFocus callback is triggered and the received isFocus parameter is true. As a result, the text displayed on the Button component is changed to Focused.

@Entry
@Component
export struct OnAccessibilityFocusCase01 {
  @State isFocus: boolean = false;

  build() {
    // ...
    Column() {
      Text('Text') // When the focus is on this component, the focus is lost. You can verify the unfocused state.
      Button(this.isFocus ? 'Focused' : 'Unfocused')
        .onAccessibilityFocus((isFocus: boolean) => {
          this.isFocus = isFocus
          console.info(`current isFocus: ${this.isFocus}`)
        })
    }
    // ...
  }
}

[h2]Accessibility Touch Event Callback

The onAccessibilityHover method provides the accessibility callback listening capability for single-finger touch operations.

The following two examples provide a comparison to demonstrate how to listen for accessibility touch events when ScreenReader is enabled.

Example 1: The Text component is used as an example. The default text displayed is "None". In accessibility mode, when the Text component is touched, the displayed text remains unchanged.

@Entry
@Component
export struct OnAccessibilityHoverCase01 {
  @State hoverText: string = 'None';

  build() {
    // ...
    Column() {
      Text(this.hoverText)
        .onTouch((event: TouchEvent) => {
          this.hoverText = 'Input text';
        })
    }
    // ...
  }
}

Example 2: After the hoverText variable is modified by configuring the onAccessibilityHover callback, when the Text component is touched, the displayed text changes to "Input text".

@Entry
@Component
export struct OnAccessibilityHoverCase02 {
  @State hoverText: string = 'None';

  build() {
    // ...
    Column() {
      Text(this.hoverText)
        .onTouch((event: TouchEvent) => {
          this.hoverText = 'Input text';
        })
        .onAccessibilityHover((isHover: boolean, event: AccessibilityHoverEvent) => {
          // Simulate click to commit text.
          this.hoverText = 'Input text';
        })
    }
    // ...
  }
}

[h2]Accessibility Click Event Callback

The onAccessibilityActionIntercept method provides the capability to intercepting accessibility control actions. Registrants can use this callback to determine whether to intercept the current accessibility action and implement custom handling. If this callback is registered for a component that does not support the click operation, the callback cannot be triggered.

The following two examples provide a comparison to demonstrate how to configure the onAccessibilityActionIntercept callback function to process click events.

Example 1: When a user clicks the Toggle component, a dialog box is displayed. ScreenReader first announces "Switch on" and then announces the content "Confirm to switch on" in the dialog box. Due to the short interval, the announcement of "Confirm to switch on" interrupts the announcement of "Switch on."

@Entry
@Component
export struct AccessibilityActionInterceptCase01 {
  @State isOn: boolean = false;

  build() {
    // ...
    Column() {
    Toggle({ type: ToggleType.Switch, isOn: this.isOn})
        .onClick(() => {
        this.getUIContext().showAlertDialog({
            title: '',
            message: this.isOn ? 'Confirm to switch off' : 'Confirm to switch on?',
            primaryButton: {
            value: 'OK',
            action: () => {
                this.isOn = !this.isOn;
            }
            },
            secondaryButton: {
            value: 'Cancel',
            action: () => {}
            }
        })
        })
    }
    // ...
  }
}

Example 2: Configure the onAccessibilityActionIntercept callback. After the click event is consumed inside the component, when the toggle is clicked, ScreenReader no longer announces "Switch on" or "Switch off". Instead, it only announces the content of the dialog box "Confirm to switch on" or "Confirm to switch off".

@Entry
@Component
export struct AccessibilityActionInterceptCase02 {
  @State isOn: boolean = false;

  build() {
    // ...
    Column() {
    Toggle({ type: ToggleType.Switch, isOn: this.isOn})
        .onClick(() => {
        })
        .onAccessibilityActionIntercept((action: AccessibilityAction) => {
        // ...
        if (action == AccessibilityAction.ACCESSIBILITY_CLICK) {
            this.getUIContext().showAlertDialog({
            title: '',
            message: this.isOn ? 'Confirm to switch off' : 'Confirm to switch on?',
            primaryButton: {
                value: 'OK',
                action: () => {
                this.isOn = !this.isOn;
                }
            },
            secondaryButton: {
                value: 'Cancel',
                action: () => {}
            }
            })
            return AccessibilityActionInterceptResult.ACTION_INTERCEPT;
        }
        return AccessibilityActionInterceptResult.ACTION_CONTINUE;
        })
    }
    // ...
  }
}

[h2]Active Focusing

If there is no default focusable element on the page, you can call the accessibility.sendAccessibilityEvent method to send an accessibility event of the requestFocusForAccessibility type to forcibly navigate the accessibility focus to a specified component. This improves the operation experience and efficiency of visually impaired users.

The following two examples provide a comparison to demonstrate how to call the sendAccessibilityEvent method to trigger active focusing.

Example 1: The Button component is used as an example. When the Text 1 button is in Visibility.Hidden state, the accessibility focus is lost on the page, meaning that no focus is present on the page.

@Entry
@Component
export struct SendAccessibilityEventCase01 {
  @State isVisible: boolean = true;

  build() {
    // ...
    Column() {
      Button('Text 1')
        .visibility(this.isVisible ? Visibility.Visible : Visibility.Hidden)
        .onClick((event: ClickEvent) => {
          this.isVisible = false;
      })

      Button('Text 2')
    }
    // ...
  }
}

Example 2: Call the accessibility.sendAccessibilityEvent method to send an active accessibility focus event of the requestFocusForAccessibility type. When the button Text 1 changes to Visibility.Hidden, the button Text 2 is focused to ensure that at least one focus exists on the page.

import { accessibility } from '@kit.AccessibilityKit';

@Entry
@Component
export struct SendAccessibilityEventCase02 {
  @State isVisible: boolean = true;

  build() {
    // ...
    Column() {
      Button('Text 1')
        .visibility(this.isVisible ? Visibility.Visible : Visibility.Hidden)
        .onClick(() => {
          this.isVisible = false;
          const event: accessibility.EventInfo = {
            type: "requestFocusForAccessibility",
            // Replace it with the actual project name.
            bundleName: "com.samples.uiextensionandaccessibility",
            triggerAction: "common",
            customId: '123'
          }
          accessibility.sendAccessibilityEvent(event);
      })

      Button('Text 2')
        .id('123') // Set the component ID.
    }
    // ...
  }
}

[h2]Active Announcement

To trigger dynamic announcement, you can call the accessibility.sendAccessibilityEvent method to send an accessibility event of the announceForAccessibility type. This improves the announcement experience for visually impaired users.

Example 1: When the text content of a Button component changes, ScreenReader does not re-announce the content, making it difficult for visually impaired users to perceive that the function of the button has changed.

@Entry
@Component
export struct SendAccessibilityEventCase03 {
  @State text: string = 'Pause'
  private isPlay: boolean = false;

  build() {
    // ...
    Column() {
      Button(this.text)
        .onClick(() => {
          this.isPlay = !this.isPlay;
          this.text = this.isPlay ? 'Pause' : 'Play'
        })
    }
    // ...
  }
}

Example 2: When the text content of the Button component changes, the accessibility.sendAccessibilityEvent method is called to send an accessibility event of the announceForAccessibility type, triggering ScreenReader to actively announce "Play" or "Pause". This ensures that the button text content change is synchronized with the announcement.

import { accessibility } from '@kit.AccessibilityKit';

@Entry
@Component
export struct SendAccessibilityEventCase04 {
  @State text: string = 'Pause'
  private isPlay: boolean = false;

  build() {
    // ...
    Column() {
      Button(this.text)
        .onClick(() => {
          this.isPlay = !this.isPlay;
          this.text = this.isPlay ? 'Pause' : 'Play'
          const event: accessibility.EventInfo = {
            type: "announceForAccessibility",
            // Replace it with the actual project name.
            bundleName: "com.samples.uiextensionandaccessibility",
            triggerAction: "common",
            textAnnouncedForAccessibility: this.text,
          }
          accessibility.sendAccessibilityEvent(event);
        })
    }
    // ...
  }
}

Querying and Listening for the Switch Status

The accessibility service can listen for and query the ScreenReader switch and touch guide status. Table 6 and Table 7 describe the APIs and their functions.

Table 6 Listening for and querying the ScreenReader switch status

Method Function
accessibility.on('screenReaderStateChange') Listens for status change events of ScreenReader being enabled or disabled.
accessibility.off('screenReaderStateChange') Cancels listening for status change events of ScreenReader being enabled or disabled.
accessibility.isScreenReaderOpenSync(): boolean Checks whether ScreenReader is enabled synchronously.

Table 7 Listening for and querying the touch guide switch status

Solution Function
accessibility.on('touchGuideStateChange') Listens for status change events of the touch guide function being enabled or disabled.
accessibility.off('touchGuideStateChange') Cancels listening for status change events of the touch guide function being enabled or disabled.
accessibility.isOpenTouchGuideSync() Synchronously checks whether the touch guide mode is currently enabled.