• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# ContextMenu
2
3The menu bound to a component through [bindContextMenu](./ts-universal-attributes-menu.md#bindcontextmenu12) on a page can be closed as needed.
4
5>  **NOTE**
6>
7> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
8>
9> Since API version 12, you can use the [getContextMenuController](../js-apis-arkui-UIContext.md#contextmenucontroller12) API in [UIContext](../js-apis-arkui-UIContext.md#uicontext) to obtain the UI context.
10
11## ContextMenu.close
12
13static close()
14
15Closes the menu bound to this component through [bindContextMenu](./ts-universal-attributes-menu.md#bindcontextmenu12) on a page.
16
17**Atomic service API**: This API can be used in atomic services since API version 11.
18
19**System capability**: SystemCapability.ArkUI.ArkUI.Full
20
21## Example
22
23This example demonstrates how to call the **ContextMenu.close** API to close a context menu that is bound to a component using **bindContextMenu**.
24
25>  **NOTE**
26>
27> For clarity in UI execution context, you are advised to use the [getContextMenuController](../js-apis-arkui-UIContext.md#contextmenucontroller12) API in [UIContext](../js-apis-arkui-UIContext.md#uicontext).
28
29```ts
30// xxx.ets
31@Entry
32@Component
33struct Index {
34  @Builder MenuBuilder() {
35    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
36      Button('Test ContextMenu1')
37      Divider().strokeWidth(2).margin(5).color(Color.Black)
38      Button('Test ContextMenu2')
39      Divider().strokeWidth(2).margin(5).color(Color.Black)
40      Button('Test ContextMenu3')
41    }
42    .width(200)
43    .height(160)
44  }
45
46  build() {
47    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
48      Column() {
49        Text("Test ContextMenu")
50          .fontSize(20)
51          .width('100%')
52          .height(500)
53          .backgroundColor(0xAFEEEE)
54          .textAlign(TextAlign.Center)
55      }
56      .bindContextMenu(this.MenuBuilder, ResponseType.LongPress)
57      .onDragStart(()=>{
58        // Close the menu when the component is dragged.
59        ContextMenu.close() // You are advised to use this.getUIContext().getContextMenuController().close().
60      })
61    }
62    .width('100%')
63    .height('100%')
64  }
65}
66```
67
68![contextmenu_close.gif](figures/contextmenu_close.gif)
69