Read the original article:Text Binding Custom Menu
Problem Description
How to achieve the following effect by binding a custom menu to the Text component:
- The menu displayed by bindSelectionMenu automatically disappears when the user touches the screen.
- Long press to bring up the custom menu; double-tap gesture does not display the default menu.
Background Knowledge
- The gesture binding method is used to bind different types of gesture events to a component and set the response methods for these events.
- The bindSelectionMenu method can set a custom selection menu for Text. For usage details, please refer to the documentation on binding custom menus to text.
Solution
- Add a click event to the outermost component of the page to close the menu, achieving the effect of the menu disappearing when the screen is touched.
- The double-tap gesture to bring up the default menu is the system default specification. You can bind a double-tap event to the Text component to override the default behavior.
@Entry
@Component
struct BindMenuPage {
controller: TextController = new TextController();
build() {
Column() {
Text(undefined, { controller: this.controller }) {
Span('Hello World');
ImageSpan($r('app.media.startIcon')) // Image resources need to be replaced by yourself.
.width('100px').height('100px');
}
.parallelGesture(
// Rewrite the double-tap gesture event to close the menu.
TapGesture({ count: 2 })
.onAction(() => {
this.controller.closeSelectionMenu();
}), GestureMask.Normal)
.copyOption(CopyOptions.InApp)
// Set TextResponseType.LONG_PRESS to display a custom menu by long-pressing.
.bindSelectionMenu(TextSpanType.DEFAULT, this.LongPressImageCustomMenu, TextResponseType.LONG_PRESS);
}.width('100%').height('100%')
.justifyContent(FlexAlign.Center)
.onClick(() => {
// Set a click event on the root node of the page to close the menu.
this.controller.closeSelectionMenu(); // Close Menu
});
}
@Builder
LongPressImageCustomMenu() {
Scroll() {
Menu() {
MenuItemGroup() {
// Image resources need to be replaced by yourself.
MenuItem({ startIcon: $r('app.media.startIcon'), content: 'Long Press Image Menu 1', labelInfo: '' });
MenuItem({ startIcon: $r('app.media.startIcon'), content: 'Long Press Image Menu 2', labelInfo: '' });
MenuItem({ startIcon: $r('app.media.startIcon'), content: 'Long Press Image Menu 3', labelInfo: '' });
};
}
.backgroundColor('#F0F0F0');
};
}
}
Verification Result
If change the content as "Menu 1":










