• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# AtomicServiceSearch
2
3<!--Kit: ArkUI-->
4<!--Subsystem: ArkUI-->
5<!--Owner: @qq_36417014-->
6<!--Designer: @zhangbeilei-->
7<!--Tester: @tinygreyy-->
8<!--Adviser: @zengyawen-->
9
10AtomicServiceSearch为开发者提供满足定制化需求的功能,内容包括默认显示的搜索区、可自定义的选择区和功能区(最多两个)。
11
12> **说明:**
13>
14> 该组件从API version 18开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
15
16
17## 导入模块
18
19```
20import { AtomicServiceSearch } from '@kit.ArkUI';
21```
22
23
24## AtomicServiceSearch
25```ts
26AtomicServiceSearch({
27  value?: ResourceStr,
28  placeholder?: ResourceStr,
29  controller?: SearchController,
30  select?: SelectParams,
31  search?: SearchParams,
32  operation?: OperationParams,
33})
34```
35
36**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
37
38**装饰器类型:** @Component
39
40**系统能力:** SystemCapability.ArkUI.ArkUI.Full
41
42**参数:**
43
44| 名称      | 类型         | 必填 | 装饰器类型 | 说明                                                         |
45| ----------- | :--------------- | ---- | ---------- | ------------------------------------------------------------ |
46| value       | [ResourceStr](ts-types.md#resourcestr) | 否 | @Prop | 设置当前显示的搜索文本内容。默认值为空字符串。 |
47| placeholder | [ResourceStr](ts-types.md#resourcestr) | 否 | @Prop | 搜索框内默认显示的提示文本。默认值为`Search`。 |
48| controller  | [SearchController](ts-basic-components-search.md#searchcontroller) | 否   | - | Search组件控制器,用于设置输入光标的位置、退出编辑态等操作。默认值为`undefined`。 |
49| select      | [SelectParams](#selectparams) | 否 | @Prop | select选择区的内容、事件及样式。默认值为`undefined`。 |
50| search      | [SearchParams](#searchparams) | 否 | @Prop | search搜索区可支持的事件及样式。默认值为`undefined`。 |
51| operation   | [OperationParams](#operationparams) | 否 | - | 选择区(右侧)的功能设置项。默认值为`undefined`。 |
52
53
54## SelectParams
55
56AtomicServiceSearch中“选择区”的可选属性。
57
58**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
59
60**系统能力:** SystemCapability.ArkUI.ArkUI.Full
61
62| 名称                    | 类型                   | 必填                         | 说明                                                         |
63| ----------------------- | -------------------------------------------- | ------------------------------------------------------------ | ---- |
64| options                 | Array&lt;[SelectOption](ts-basic-components-select.md#selectoption对象说明)&gt; | 否 | 下拉选项内容。默认值为`undefined`。 |
65| selected                | number| 否 | 设置下拉菜单初始选项的索引。第一项的索引为0。当不设置selected属性时,默认选择值为-1,菜单项不选中。 |
66| selectValue             | [ResourceStr](ts-types.md#resourcestr) | 否 | 设置下拉按钮本身的文本内容。默认值为`undefined`。 |
67| onSelect                | [OnSelectCallback](#onselectcallback) | 否 | 下拉菜单选中某一项的回调。默认值为`undefined`。 |
68| menuItemContentModifier | [ContentModifier&lt;MenuItemConfiguration&gt;](ts-basic-components-select.md#menuitemconfiguration12对象说明) | 否 | 	在Select组件上,定制下拉菜单项内容区的方法。在应用了该属性后,下拉菜单的内容将完全由开发者自定义,此时为选择区设置的下拉菜单分割线、背景色及字体样式等属性将不再生效。<br/>modifier: 内容修改器,开发者需要自定义class实现ContentModifier接口。默认值为`undefined`。 |
69| divider                 | [Optional](ts-universal-attributes-custom-property.md#optionalt12)&lt;[DividerOptions](ts-basic-components-textpicker.md#divideroptions12对象说明)&gt; \| null | 否 | 1.设置DividerOptions,则按设置的样式显示分割线。默认值:`{strokeWidth: '1px', color: '#33182431'}`。<br/>2.设置为null时,不显示分割线。<br/>3.strokeWidth设置过宽时,会覆盖文字。分割线会从每一个Item底部开始,同时向上向下画分割线。<br/>4.startMargin和endMargin的默认值与不设置divider属性时的分割线样式保持一致。startMargin和endMargin的和与optionWidth的值相等时,不显示分割线。 startMargin和endMargin的和超过optionWidth的值时,按照默认样式显示分割线。 |
70| font                    | [Font](ts-types.md#font) | 否 | 下拉按钮本身的文本样式。默认值:`{size: $r('sys.float.ohos_id_text_size_body1')}`。 |
71| fontColor               | [ResourceColor](ts-types.md#resourcecolor) | 否 | 下拉菜单选中项的文本颜色。默认值:`{fontColor: $r('sys.color.ohos_id_color_text_primary')}`。   |
72| selectedOptionBgColor   | [ResourceColor](ts-types.md#resourcecolor) | 否 | 下拉菜单选中项的背景色。默认值:`$r('sys.color.ohos_id_color_component_activated')`混合`$r('sys.color.ohos_id_alpha_highlight_bg')`的透明度。 |
73| selectedOptionFont      | [Font](ts-types.md#font) | 否 | 下拉菜单选中项的文本样式。默认值:`{size:&nbsp;$r('sys.color.ohos_id_text_size_body1'), weight:&nbsp;FontWeight.Regular}`。 |
74| selectedOptionFontColor | [ResourceColor](ts-types.md#resourcecolor) | 否 | 下拉菜单选中项的文本颜色。默认值:`$r('sys.color.ohos_id_color_text_primary_activated')`。 |
75| optionBgColor           | [ResourceColor](ts-types.md#resourcecolor) | 否 | 下拉菜单项的背景色。默认值:`Color.Transparent`。 |
76| optionFont              | [Font](ts-types.md#font) | 否 | 下拉菜单项的文本样式。默认值:`{size:&nbsp;$r('sys.float.ohos_id_text_size_body1'), weight:&nbsp;FontWeight.Regular}`。 |
77| optionFontColor         | [ResourceColor](ts-types.md#resourcecolor) | 否 | 下拉菜单项的文本颜色。默认值:`$r('sys.color.ohos_id_color_text_primary')`。 |
78| optionWidth             | [Dimension](ts-types.md#dimension10) \| [OptionWidthMode](ts-appendix-enums.md#optionwidthmode11) | 否 | 设置下拉菜单项的宽度,不支持设置百分比。OptionWidthMode类型为枚举类型,OptionWidthMode决定下拉菜单是否继承下拉按钮宽度。当设置为异常值或小于最小宽度56vp时,属性不生效,菜单项宽度设为默认值,即菜单默认宽度为2栅格。 |
79| optionHeight            | [Dimension](ts-types.md#dimension10) | 否 | 设置下拉菜单显示的最大高度,不支持设置百分比。下拉菜单的默认最大高度是屏幕可用高度的80%,设置的菜单最大高度不能超过默认最大高度。 |
80| space                   | [Length](ts-types.md#length) | 否 | 下拉菜单项的文本与箭头之间的间距。默认值:`8`。 |
81| arrowPosition           | [ArrowPosition](ts-basic-components-select.md#arrowposition10枚举说明) | 否 | 下拉菜单项的文本与箭头之间的对齐方式。默认值:`ArrowPosition.END`。 |
82| menuAlign               | [MenuAlignParams](#menualignparams) | 否 | 设置下拉按钮与下拉菜单间的对齐方式。默认值:`{alignType: MenuAlignType.START,   offset: {dx: 0, dy: 0}}`。 |
83| menuBackgroundColor     | [ResourceColor](ts-types.md#resourcecolor) | 否 | 下拉菜单的背景色。默认值:`Color.Transparent`。   |
84| menuBackgroundBlurStyle | [BlurStyle](ts-universal-attributes-background.md#blurstyle9) | 否 | 下拉菜单的背景模糊材质。默认值:`BlurStyle.COMPONENT_ULTRA_THICK`。 |
85
86
87## SearchParams
88
89AtomicServiceSearch中“搜索区”的可选属性。
90
91**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
92
93**系统能力:** SystemCapability.ArkUI.ArkUI.Full
94
95| 名称                     | 类型            | 必填                                   | 说明                                                         |
96| ------------------------ | ---------------------------------------------- | ------------------------------------------------------------ | ---- |
97| searchKey | [ResourceStr](ts-types.md#resourcestr) | 否 | 用作找到一个唯一的search组件。默认值:`undefined`。   |
98| componentBackgroundColor | [ResourceColor](ts-types.md#resourcecolor) | 否 | 设置组件的背景色。默认值:`$r('sys.color.ohos_id_color_text_field_sub_bg')`。   |
99| pressedBackgroundColor   | [ResourceColor](ts-types.md#resourcecolor) | 否 | 设置组件按压态的背景色。默认值:`$r('sys.color.ohos_id_color_click_effect')`。 |
100| searchButton             | [SearchButtonParams](#searchbuttonparams) | 否 | 设置搜索框末尾搜索按钮。点击搜索按钮,同时触发onSubmit与onClick回调。<br />-value:搜索框末尾搜索按钮文本内容。<br /> -option: 配置搜索框文本样式。默认值:`{fontSize: '16fp', fontColor: '#ff3f97e9'}`。 |
101| placeholderColor         | [ResourceColor](ts-types.md#resourcecolor) | 否 | placeholder文本颜色。默认值:`$r('sys.color.ohos_id_color_text_secondary')`。   |
102| placeholderFont          | [Font](ts-types.md#font) | 否 | 设置placeholder文本样式,包括字体大小,字体粗细,字体族,字体风格。默认值:`{size: $r('sys_float.ohos_id_text_size_body1')}`。 |
103| textFont                 | [Font](ts-types.md#font) | 否 | 设置搜索框内输入文本样式,包括字体大小,字体粗细,字体族,字体风格。目前仅支持默认字体族。默认值:`{size: $r('sys_float.ohos_id_text_size_body1')}`。 |
104| textAlign                | [TextAlign](ts-appendix-enums.md#textalign) | 否 | 文本在搜索框中的对齐方式。默认值:`TextAlign.Start`。   |
105| copyOptions              | [CopyOptions](ts-appendix-enums.md#copyoptions9) | 否 | 输入的文本是否可复制。默认值:`CopyOptions.LocalDevice`,支持设备内复制。   |
106| searchIcon               | [IconOptions](ts-basic-components-search.md#iconoptions10对象说明) \| [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | 否 | 左侧搜索图标样式。<br />浅色模式默认值:`{size: '16vp', color: '#99182431', src: ' '}`。<br />深色模式默认值:`{size: '16vp', color: '#99ffffff', src: ' '}`。  |
107| cancelIcon               | [IconOptions](ts-basic-components-search.md#iconoptions10对象说明) | 否 | 右侧清除按钮样式。默认值:`{style: CancelButtonStyle.INPUT, icon: {size: '16vp', color: '#99ffffff', src: ' '}}`。<br/>当style为CancelButtonStyle.CONSTANT时,默认显示清除样式。   |
108| fontColor                | [ResourceColor](ts-types.md#resourcecolor) | 否 |  输入文本的字体颜色。默认值:`$r('sys.color.ohos_id_color_text_secondary')`。 |
109| caretStyle               | [CaretStyle](ts-text-common.md#caretstyle10) | 否 | 光标样式。默认值:`{width: '1.5vp', color: '#007DFF'}`。   |
110| enableKeyboardOnFocus    | boolean | 否 | Search获焦时,是否主动拉起软键盘。默认值:`true`。   |
111| hideSelectionMenu        | boolean | 否 | 是否不弹出系统文本选择菜单。<br />设置为true时,单击输入框光标、长按输入框、双击输入框、三击输入框或者右键输入框,不弹出系统文本选择菜单。设置为false时,弹出系统文本选择菜单。默认值:`false`。   |
112| type                     | [SearchType](ts-basic-components-search.md#searchtype11枚举说明) | 否 | 输入框类型。默认值:`SearchType.Normal`。   |
113| maxLength                | number | 否 | 设置文本的最大输入字符数。默认不设置最大输入字符数限制。到达文本最大字符限制,将无法继续输入字符。默认值:`-1`。  |
114| enterKeyType             | [EnterKeyType](ts-basic-components-textinput.md#enterkeytype枚举说明) | 否 | 输入法回车键类型。默认值:`EnterKeyType.Search`。   |
115| decoration               | [TextDecorationOptions](ts-universal-attributes-text-style.md#textdecorationoptions12对象说明) | 否 |  文本装饰线对象。默认值:`{type: TextDecorationType.None, color: Color.Black, style: TextDecorationStyle.SOLID}`。   |
116| letterSpacing            | number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | 否 | 设置文本字符间距。正数拉开字符距离,负数则拉近字符距离。浮点数默认值为0.0,单位为物理像素px。若输入类型非number且无法解析为数字,则使用默认值。  |
117| fontFeature              | [ResourceStr](ts-types.md#resourcestr) | 否 | 设置文字特性效果,比如数字等宽的特性。<br />格式为:normal \| \<feature-tag-value\><br />\<feature-tag-value\>的格式为:\<string\> \[ \<integer\> \| on \| off ]<br />\<feature-tag-value\>的个数可以有多个,中间用','隔开。<br />例如,使用等宽数字的输入格式为:"ss01" on。默认值为`undefined`。   |
118| selectedBackgroundColor  | [ResourceColor](ts-types.md#resourcecolor) | 否 | 文本选中底板颜色。默认为20%不透明度。 |
119| inputFilter              | [InputFilterParams](#inputfilterparams) | 否 | 通过正则表达式设置输入过滤器。匹配表达式的输入允许显示,不匹配的输入将被过滤。仅支持单个字符匹配,不支持字符串匹配。默认值为`undefined`。<br /> -value: 正则表达式。 <br /> -error: 正则匹配失败时,返回被过滤的内容。 |
120| textIndent               | [Dimension](ts-types.md#dimension10) | 否 | 首行文本缩进。默认值:`0`。   |
121| minFontSize              | number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | 否 | 设置文本最小显示字号。需要配合maxFontSize以及布局大小限制使用,单独设置不生效。默认值为`undefined`。   |
122| maxFontSize              | number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | 否 | 设置文本最大显示字号。需要配合minFontSize以及布局大小限制使用,单独设置不生效。默认值为`undefined`。   |
123| editMenuOptions          | [EditMenuOptions](ts-text-common.md#editmenuoptions) | 否 | 设置自定义菜单扩展项,允许用户设置扩展项的文本内容、图标、回调方法。默认值为`undefined`。   |
124| enablePreviewText        | boolean | 否 | 是否开启输入预上屏。默认值:`true`。 <br/> 需要配合开启输入法的预上屏功能。预上屏内容定义为文字暂存态,目前不支持文字拦截功能,因此该值为true时不触发onWillInsert、onDidInsert回调。  |
125| enableHapticFeedback     | boolean | 否 | 是否开启触控反馈。默认值:`true`。   |
126| onSubmit                 | Callback&lt;string&gt; \| [SearchSubmitCallback](ts-basic-components-search.md#searchsubmitcallback14) | 否 | 点击搜索图标、搜索按钮或者按下软键盘搜索按钮时触发该回调。默认值为`undefined`。   |
127| onChange                 | [EditableTextOnChangeCallback](ts-text-common.md#editabletextonchangecallback12) | 否 | 输入内容发生变化时,触发该回调。默认值为`undefined`。   |
128| onCopy                   | Callback&lt;string&gt; | 否 | 进行复制操作时,触发该回调。默认值为`undefined`。   |
129| onCut                    | Callback&lt;string&gt; | 否 | 进行剪切操作时,触发该回调。默认值为`undefined`。   |
130| onPaste                  | [OnPasteCallback](#onpastecallback) | 否 | 进行粘贴操作时,触发该回调。默认值为`undefined`。   |
131| onTextSelectionChange    | [OnTextSelectionChangeCallback](#ontextselectionchangecallback) | 否 | 文本选择的位置发生变化或编辑状态下光标位置发生变化时,触发该回调。默认值为`undefined`。   |
132| onContentScroll          | [OnContentScrollCallback](#oncontentscrollcallback) | 否 | 文本内容滚动时,触发该回调。默认值为`undefined`。   |
133| onEditChange             | Callback&lt;boolean&gt; | 否 | 输入状态变化时,触发该回调。有光标时为编辑态,无光标时为非编辑态。isEditing为true表示正在输入。默认值为`undefined`。   |
134| onWillInsert             | Callback&lt;[InsertValue](ts-text-common.md#insertvalue12对象说明), boolean&gt; | 否 | 在将要输入时,触发该回调。默认值为`undefined`。   |
135| onDidInsert              | Callback&lt;[InsertValue](ts-text-common.md#insertvalue12对象说明)&gt; | 否 | 在输入完成时,触发该回调。默认值为`undefined`。   |
136| onWillDelete             | Callback&lt;[DeleteValue](ts-text-common.md#deletevalue12对象说明), boolean&gt; | 否 | 在将要删除时,触发该回调。默认值为`undefined`。   |
137| onDidDelete              | Callback&lt;[DeleteValue](ts-text-common.md#deletevalue12对象说明)&gt; | 否 | 在删除完成时,触发该回调。默认值为`undefined`。   |
138
139## OperationParams
140
141AtomicServiceSearch中“功能区”的初始化参数。
142
143**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
144
145**系统能力:** SystemCapability.ArkUI.ArkUI.Full
146
147| 名称          | 类型        | 必填  | 说明                          |
148| ------------- | --------------- | ---------------------------- | ---- |
149| auxiliaryItem | [OperationOption ](ohos-arkui-advanced-SubHeader.md#operationoption)| 否 | 附属于搜索区(右侧)的功能位。默认值为`undefined`。 |
150| independentItem | [OperationOption ](ohos-arkui-advanced-SubHeader.md#operationoption)| 否 | 独立于搜索区(右侧)的功能位。默认值为`undefined`。 |
151
152
153## InputFilterParams
154
155搜索框过滤设置项。
156
157**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
158
159**系统能力:** SystemCapability.ArkUI.ArkUI.Full
160
161| 名称             | 类型         | 必填 | 说明                               |
162| ---------------- | ---------------- | ---- | ---------------------------------- |
163| inputFilterValue | [ResourceStr](ts-types.md#resourcestr) | 是 | 正则表达式。 |
164| error | Callback&lt;string&gt; | 否 | 正则匹配失败时,返回被过滤的内容。默认值为`undefined`。 |
165
166## SearchButtonParams
167
168搜索框末尾搜索按钮设置项。
169
170**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
171
172**系统能力:** SystemCapability.ArkUI.ArkUI.Full
173
174| 名称              | 类型            | 必填 | 说明                                                         |
175| ----------------- | ------------------- | ---- | ------------------------------------------------------------ |
176| searchButtonValue | [ResourceStr](ts-types.md#resourcestr) | 是   | 搜索框末尾搜索按钮文本内容。 |
177| options | [SearchButtonOptions](ts-basic-components-search.md#searchbuttonoptions10对象说明) | 否   | 配置搜索框文本样式。默认值:`{fontSize: '16fp',fontColor: '#ff3f97e9'}`。 |
178
179
180## MenuAlignParams
181
182下拉按钮与下拉菜单间的对齐方式设置项。
183
184**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
185
186**系统能力:** SystemCapability.ArkUI.ArkUI.Full
187
188| 名称      | 类型      | 必填 | 说明                                                         |
189| --------- | ------------- | ---- | ------------------------------------------------------------ |
190| alignType | [MenuAlignType](ts-basic-components-select.md#menualigntype10枚举说明) | 是 | 对齐方式类型。默认值:`MenuAlignType.START`。 |
191| offset | [Offset](ts-types.md#offset) | 否 | 按照对齐类型对齐后,下拉菜单相对下拉按钮的偏移量。默认值:`{dx: 0, dy: 0}`。 |
192
193
194## OnSelectCallback
195
196type OnSelectCallback = (index: number, selectValue: string) => void
197
198下拉菜单选中某一项的回调。
199
200**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
201
202**系统能力:** SystemCapability.ArkUI.ArkUI.Full
203
204**参数:**
205
206| 参数名   | 类型                                                         | 必填 | 说明                                                     |
207| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------------------- |
208| index | number | 是 | 选中项的索引,索引从0开始。 |
209| selectValue | string | 是 | 选中项的值。 |
210
211
212## OnPasteCallback
213
214type OnPasteCallback = (pasteValue: string, event: PasteEvent) => void
215
216进行粘贴操作时,触发该回调。
217
218**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
219
220**系统能力:** SystemCapability.ArkUI.ArkUI.Full
221
222**参数:**
223
224| 参数名   | 类型                                                         | 必填 | 说明                                                     |
225| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------------------- |
226| pasteValue | string | 是 | 要粘贴的文本内容。 |
227| event | [PasteEvent](ts-basic-components-richeditor.md#pasteevent11) | 是 | 用户自定义粘贴事件。 |
228
229
230## OnTextSelectionChangeCallback
231
232type OnTextSelectionChangeCallback = (selectionStart: number, selectionEnd: number) => void
233
234文本选择的位置发生变化或编辑状态下光标位置发生变化时,触发该回调。
235
236**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
237
238**系统能力:** SystemCapability.ArkUI.ArkUI.Full
239
240**参数:**
241
242| 参数名   | 类型                                                         | 必填 | 说明                                                     |
243| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------------------- |
244| selectionStart | number | 是 | 文本选择区域的起始位置。 |
245| selectionEnd | number | 是 | 文本选择区域的结束位置。 |
246
247
248## OnContentScrollCallback
249
250type OnContentScrollCallback = (totalOffsetX: number, totalOffsetY: number) => void
251
252文本内容滚动时,触发该回调。
253
254**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
255
256**系统能力:** SystemCapability.ArkUI.ArkUI.Full
257
258**参数:**
259
260| 参数名   | 类型                                                         | 必填 | 说明                                                     |
261| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------------------- |
262| totalOffsetX | number | 是 | 文本左上角横坐标相较于整个内容输入区左上角横坐标的偏移量。 |
263| totalOffsetY | number | 是 | 文本左上角纵坐标相较于整个内容输入区左上角纵坐标的偏移量。 |
264
265
266## 示例
267
268### 示例1(AtomicServiceSearch添加选择区)
269该示例通过select参数为AtomicServiceSearch组件添加左侧选择区。
270
271```ts
272import { AtomicServiceSearch } from '@kit.ArkUI';
273
274@Entry
275@Component
276struct Index {
277  build() {
278    Column({ space: 6 }) {
279      Text('AtomicServiceSearch添加选择区').alignSelf(ItemAlign.Start).decoration({
280        type: TextDecorationType.Underline,
281        color: Color.Black,
282        style: TextDecorationStyle.SOLID
283      }).margin({ top: 20, bottom: 20 })
284
285      AtomicServiceSearch({
286        select: {
287          options: [
288            { value: 'Select1', icon: $r("app.media.sweep") }, // 自定义资源
289            { value: 'Select2', icon: $r("app.media.sweep") }, // 自定义资源
290            { value: 'Select3', icon: $r("app.media.sweep") }, // 自定义资源
291            { value: 'Select4', icon: $r("app.media.sweep") } // 自定义资源
292          ],
293          selected: -1,
294          selectValue: 'Select1',
295          onSelect: (index: number, selectValue: string) => { // 自定义事件
296            if (index === 0) {
297              this.alert(`index: ${index}, selectValue: ${selectValue}`);
298            } else if (index === 1) {
299              this.alert(`index: ${index}, selectValue: ${selectValue}`);
300            } else if (index === 2) {
301              this.alert(`index: ${index}, selectValue: ${selectValue}`);
302            } else if (index === 3) {
303              this.alert(`index: ${index}, selectValue: ${selectValue}`);
304            }
305          },
306        }
307      })
308    }.padding({ left: 16, right: 16 })
309  }
310
311  private alert(message: string): void {
312    this.getUIContext().showAlertDialog({ message: message });
313  }
314}
315```
316
317![](figures/AtomicServiceSearchDemo01.gif)
318
319
320
321### 示例2(AtomicServiceSearch添加功能位)
322该示例通过operation参数为AtomicServiceSearch组件添加右侧功能位。
323
324```ts
325import { AtomicServiceSearch } from '@kit.ArkUI';
326
327@Entry
328@Component
329struct Index {
330  build() {
331    Column({ space: 6 }) {
332      Text('AtomicServiceSearch添加功能位').alignSelf(ItemAlign.Start).decoration({
333        type: TextDecorationType.Underline,
334        color: Color.Black,
335        style: TextDecorationStyle.SOLID
336      }).margin({ top: 20, bottom: 20 })
337
338      AtomicServiceSearch({
339        operation: {
340          // 附属于Search组件的功能位
341          auxiliaryItem: {
342            value: $r("app.media.sweep"), // 自定义资源
343            action: () => {
344              this.alert('扫一扫'); // 自定义事件
345            }
346          },
347          // 独立于Search组件的功能位
348          independentItem: {
349            value: $r("app.media.dingding"), // 自定义资源
350            action: () => {
351              this.alert('通知'); // 自定义事件
352            }
353          }
354        }
355      })
356    }.padding({ left: 16, right: 16 })
357  }
358
359  private alert(message: string): void {
360    this.getUIContext().showAlertDialog({ message: message });
361  }
362}
363```
364
365![](figures/AtomicServiceSearchDemo02.gif)
366
367
368
369### 示例3(AtomicServiceSearch添加选择区及功能位)
370该示例中为AtomicServiceSearch组件同时添加左侧选择区和右侧功能位。
371
372```ts
373import { AtomicServiceSearch } from '@kit.ArkUI';
374
375@Entry
376@Component
377struct Index {
378  build() {
379    Column({ space: 6 }) {
380      Text('AtomicServiceSearch+选择区+功能位').alignSelf(ItemAlign.Start).decoration({
381        type: TextDecorationType.Underline,
382        color: Color.Black,
383        style: TextDecorationStyle.SOLID
384      }).margin({ top: 20, bottom: 20 })
385
386      AtomicServiceSearch({
387        select: {
388          options: [
389            { value: 'Select1', icon: $r("app.media.sweep") }, // 自定义资源
390            { value: 'Select2', icon: $r("app.media.sweep") }, // 自定义资源
391            { value: 'Select3', icon: $r("app.media.sweep") }, // 自定义资源
392            { value: 'Select4', icon: $r("app.media.sweep") } // 自定义资源
393          ],
394          selected: -1,
395          selectValue: 'Select1',
396          onSelect: (index: number, selectValue:string) => {
397            if (index === 0) {
398              this.alert(`index: ${index}, selectValue: ${selectValue}`);
399            } else if (index === 1) {
400              this.alert(`index: ${index}, selectValue: ${selectValue}`);
401            } else if (index === 2) {
402              this.alert(`index: ${index}, selectValue: ${selectValue}`);
403            } else if (index === 3) {
404              this.alert(`index: ${index}, selectValue: ${selectValue}`);
405            }
406          },
407        },
408        operation: {
409          auxiliaryItem: {
410            value: $r("app.media.sweep"), // 自定义资源
411            action: () => {
412              this.alert('扫一扫'); // 自定义事件
413            }
414          },
415          independentItem: {
416            value: $r("app.media.dingding"), // 自定义资源
417            action: () => {
418              this.alert('通知'); // 自定义事件
419            }
420          }
421        }
422      })
423    }.padding({ left: 16, right: 16 })
424  }
425
426  private alert(message: string): void {
427    this.getUIContext().showAlertDialog({ message: message });
428  }
429}
430```
431
432![](figures/AtomicServiceSearchDemo03.gif)
433
434
435
436### 示例4(search回调事件)
437该示例通过onWillInsert、onDidInsert、onWillDelete、onDidDelete接口实现了插入和删除的功能。
438通过onSubmit接口实现了搜索区内容提交的功能。
439通过onChange接口实现了监听搜索区内容变化的功能。
440
441```ts
442import { AtomicServiceSearch } from '@kit.ArkUI';
443
444@Entry
445@Component
446struct Index {
447  @State insertValue: string = "";
448  @State deleteValue: string = "";
449  @State insertOffset: number = 0;
450  @State deleteOffset: number = 0;
451  @State deleteDirection: number = 0;
452  @State startIndex: number = 0;
453  @State endIndex: number = 0;
454  @State offsetX: number = 0;
455  @State offsetY: number = 0;
456  @State changeValue: string = '';
457  @State value: string = 'false';
458  @State submitValue: string = '';
459  @State text: string = 'Search editMenuOptions';
460
461  build() {
462    Column({ space: 6 }) {
463      Text('AtomicServiceSearch绑定事件').alignSelf(ItemAlign.Start).decoration({
464        type: TextDecorationType.Underline,
465        color: Color.Black,
466        style: TextDecorationStyle.SOLID
467      }).margin({ top: 20, bottom: 20 })
468
469      Column({ space: 6 }) {
470        Text('editing: ' + this.value).width('100%').height(25).borderRadius(15).padding({ left: 15 })
471          .backgroundColor('rgba(0, 0, 0, 0.1)').maxLines(1).textOverflow({ overflow: TextOverflow.MARQUEE });
472        Text('onSubmit:' + this.submitValue).width('100%').height(25).borderRadius(15).padding({ left: 15 })
473          .backgroundColor('rgba(0, 0, 0, 0.1)').maxLines(1).textOverflow({ overflow: TextOverflow.MARQUEE });
474        Text('onChange:' + this.changeValue).width('100%').height(25).borderRadius(15).padding({ left: 15 })
475          .backgroundColor('rgba(0, 0, 0, 0.1)').maxLines(1).textOverflow({ overflow: TextOverflow.MARQUEE });
476        Text('offset x:' + this.offsetX + ' y:' + this.offsetY).width('100%').height(25).borderRadius(15).padding({ left: 15 })
477          .backgroundColor('rgba(0, 0, 0, 0.1)').maxLines(1).textOverflow({ overflow: TextOverflow.MARQUEE });
478        Text("insertValue:" + this.insertValue + "  insertOffset:" + this.insertOffset).width('100%').height(25)
479          .borderRadius(15).padding({ left: 15 }).backgroundColor('rgba(0, 0, 0, 0.1)').maxLines(1)
480          .textOverflow({ overflow: TextOverflow.MARQUEE });
481        Text("deleteValue:" + this.deleteValue + "  deleteOffset:" + this.deleteOffset).width('100%').height(25)
482          .borderRadius(15).padding({ left: 15 }).backgroundColor('rgba(0, 0, 0, 0.1)').maxLines(1)
483          .textOverflow({ overflow: TextOverflow.MARQUEE });
484        Text("deleteDirection:" + (this.deleteDirection == 0 ? "BACKWARD" : "FORWARD")).width('100%').height(25)
485          .borderRadius(15).padding({ left: 15 }).backgroundColor('rgba(0, 0, 0, 0.1)').maxLines(1)
486          .textOverflow({ overflow: TextOverflow.MARQUEE });
487        AtomicServiceSearch({
488          select: {
489            options: [
490              { value: 'Select1', icon: $r("app.media.sweep") },
491              { value: 'Select2', icon: $r("app.media.sweep") },
492              { value: 'Select3', icon: $r("app.media.sweep") },
493              { value: 'Select4', icon: $r("app.media.sweep") }
494            ],
495            selected: -1,
496            selectValue: 'Select1',
497            onSelect: (index: number) => {
498              if (index === 0) {
499                this.alert('Select1');
500              } else if (index === 1) {
501                this.alert('Select2');
502              } else if (index === 2) {
503                this.alert('Select3');
504              } else if (index === 3) {
505                this.alert('Select4');
506              }
507            },
508          },
509          search: {
510            onSubmit: (value: string) => {
511              this.submitValue = value
512            },
513            onChange: (value: string) => {
514              this.changeValue = value
515            },
516            onCopy: () => {
517              this.alert('onCopy');
518            },
519            onCut: () => {
520              this.alert('onCut');
521            },
522            onPaste: () => {
523              this.alert('onPaste');
524            },
525            onTextSelectionChange: (selectionStart: number, selectionEnd: number) => {
526              this.startIndex = selectionStart
527              this.endIndex = selectionEnd
528            },
529            onContentScroll: (totalOffsetX: number, totalOffsetY: number) => {
530              this.offsetX = totalOffsetX
531              this.offsetY = totalOffsetY
532            },
533            onEditChange: (data: boolean) => {
534              this.value = data ? 'true' : 'false'
535            },
536            onWillInsert: (info: InsertValue) => {
537              this.insertValue = info.insertValue
538              return true;
539            },
540            onDidInsert: (info: InsertValue) => {
541              this.insertOffset = info.insertOffset
542            },
543            onWillDelete: (info: DeleteValue) => {
544              this.deleteValue = info.deleteValue
545              info.direction
546              return true;
547            },
548            onDidDelete: (info: DeleteValue) => {
549              this.deleteOffset = info.deleteOffset
550              this.deleteDirection = info.direction
551            }
552          }
553        })
554      }
555    }.padding({ left: 16, right: 16 })
556  }
557
558  private alert(message: string): void {
559    this.getUIContext().showAlertDialog({ message: message });
560  }
561}
562```
563
564![](figures/AtomicServiceSearchDemo04.gif)
565
566
567### 示例5(AtomicServiceSearch修改样式)
568该示例通过search、select、value、placeholder参数实现了AtomicServiceSearch组件样式的自定义。
569
570```ts
571import { AtomicServiceSearch, SearchParams, SelectParams } from '@kit.ArkUI';
572
573@Entry
574@Component
575struct Index {
576  @State private placeholder: string = 'Type to Search...';
577  @State private defaultValue: string = 'default';
578  @State private search?: SearchParams = {};
579  @State private select?: SelectParams = {
580    options: [
581      { value: 'Select1', icon: $r("app.media.sweep") },
582      { value: 'Select2', icon: $r("app.media.sweep") },
583      { value: 'Select3', icon: $r("app.media.sweep") },
584      { value: 'Select4', icon: $r("app.media.sweep") }
585    ],
586    selected: -1,
587    selectValue: 'Select1',
588    onSelect: (index: number) => {
589      if (index === 0) {
590        this.alert('Select1');
591      } else if (index === 1) {
592        this.alert('Select2');
593      } else if (index === 2) {
594        this.alert('Select3');
595      } else if (index === 3) {
596        this.alert('Select4');
597      }
598    }
599  };
600
601  build() {
602    Column({ space: 8 }) {
603      Text('AtomicServiceSearch修改样式').alignSelf(ItemAlign.Start).decoration({
604        type: TextDecorationType.Underline,
605        color: Color.Black,
606        style: TextDecorationStyle.SOLID
607      }).margin({ top: 20, bottom: 20 })
608
609      AtomicServiceSearch({
610        value: this.defaultValue,
611        placeholder: this.placeholder,
612        select: this.select,
613        search: this.search,
614        operation: {
615          independentItem: {
616            value: $r(`app.media.dingding`),
617            action: () => {
618              this.alert('通知');
619            }
620          }
621        }
622      })
623      Button("修改placeholder")
624        .width('100%')
625        .type(ButtonType.Normal)
626        .borderRadius(20)
627        .onClick(() => {
628          if (this.placeholder === 'Search...') {
629            this.placeholder = 'Type to Search...';
630          } else {
631            this.placeholder = 'Search...';
632          }
633        });
634      Button("修改defaultValue")
635        .width('100%')
636        .type(ButtonType.Normal)
637        .borderRadius(20)
638        .onClick(() => {
639          if (this.defaultValue === 'value') {
640            this.defaultValue = 'defaultValue';
641          } else {
642            this.defaultValue = 'value';
643          }
644        });
645      Button("修改Select样式")
646        .width('100%')
647        .type(ButtonType.Normal)
648        .borderRadius(20)
649        .onClick(() => {
650          this.select = {
651            options: [
652              { value: '选项1', icon: $r("app.media.dingding") },
653              { value: '选项2', icon: $r("app.media.dingding") },
654            ],
655            selected: -1,
656            selectValue: '选项1',
657            onSelect: (index: number) => {
658              if (index === 0) {
659                this.alert('选项1');
660              } else if (index === 1) {
661                this.alert('选项2');
662              }
663            }
664          };
665        });
666
667      Button("修改Search样式")
668        .width('100%')
669        .type(ButtonType.Normal)
670        .borderRadius(20)
671        .onClick(() => {
672          this.search = {
673            componentBackgroundColor: '#e0eee8'
674          }
675        });
676    }.padding({ left: 16, right: 16 })
677  }
678
679  private alert(message: string): void {
680    this.getUIContext().showAlertDialog({ message: message });
681  }
682}
683```
684
685![](figures/AtomicServiceSearchDemo05.gif)
686
687
688
689
690### 示例6(通过controller实现光标位置的设置)
691该示例通过controller参数实现了光标位置的设置、选择指定区域中的内容及关闭编辑状态的功能。
692
693
694```ts
695import { AtomicServiceSearch } from '@kit.ArkUI';
696
697@Entry
698@Component
699struct Index {
700  controller: SearchController = new SearchController();
701
702  build() {
703    Column({ space : 10 }) {
704      Text('通过controller实现光标位置的设置').alignSelf(ItemAlign.Start).decoration({
705        type: TextDecorationType.Underline,
706        color: Color.Black,
707        style: TextDecorationStyle.SOLID
708      }).margin({ top: 20, bottom: 20 })
709
710      AtomicServiceSearch(
711        {
712          value: 'Default Value',
713          placeholder: 'Type to Search...',
714          controller: this.controller,
715          search: {
716            searchButton: {
717              searchButtonValue: 'SEARCH',
718              options: { fontSize: '12fp', fontColor: '#ff0e1216' }
719            }
720          }
721        },
722      );
723      Button('caretPosition to 1').onClick(() => {
724        this.controller.caretPosition(1);
725      }).width('100%')
726      Button('stopEditing').onClick(() => {
727        this.controller.stopEditing();
728      }).width('100%')
729      Button('Selection [0,3]').onClick(() => {
730        this.controller.setTextSelection(0, 3)
731      }).width('100%')
732    }.padding({ left: 16, right: 16 })
733  }
734
735  public alert(message: string): void {
736    this.getUIContext().showAlertDialog({ message: message });
737  }
738}
739```
740
741![](figures/AtomicServiceSearchDemo06.gif)
742
743
744
745
746### 示例7(设置输入法回车键类型)
747该示例通过enterKeyType属性实现了动态切换输入法回车键的效果。
748
749```ts
750import { AtomicServiceSearch } from '@kit.ArkUI';
751
752@Entry
753@Component
754struct Index {
755  @State enterTypes: Array<EnterKeyType> = [EnterKeyType.Go, EnterKeyType.Search, EnterKeyType.Send, EnterKeyType.Done, EnterKeyType.Next, EnterKeyType.PREVIOUS, EnterKeyType.NEW_LINE]
756  @State index: number = 0
757
758  build() {
759    Column({ space : 10 }) {
760      Text('输入法回车键类型为搜索').alignSelf(ItemAlign.Start).decoration({
761        type: TextDecorationType.Underline,
762        color: Color.Black,
763        style: TextDecorationStyle.SOLID
764      }).margin({ top: 20, bottom: 20 })
765
766      AtomicServiceSearch({
767        placeholder: '输入法回车键类型为搜索',
768        search: {
769          enterKeyType: this.enterTypes[this.index]
770        }
771      })
772
773      Button('改变EnterKeyType').onClick(() => {
774        this.index = (this.index + 1) % this.enterTypes.length;
775      }).width('100%')
776
777    }.padding({ left: 16, right: 16 })
778  }
779
780  public alert(message: string): void {
781    this.getUIContext().showAlertDialog({ message: message });
782  }
783}
784```
785
786![](figures/AtomicServiceSearchDemo07.gif)
787
788
789
790### 示例8(设置文字特性效果)
791该示例通过fontFeature属性实现了文本在不同文字特性下的展示效果。
792
793```ts
794​​​​import { AtomicServiceSearch } from '@kit.ArkUI';
795
796@Entry
797@Component
798struct Index {
799  build() {
800    Column({ space : 10 }) {
801      Text('设置文字特性效果').alignSelf(ItemAlign.Start).decoration({
802        type: TextDecorationType.Underline,
803        color: Color.Black,
804        style: TextDecorationStyle.SOLID
805      }).margin({ top: 20, bottom: 20 })
806
807      AtomicServiceSearch({
808        value: 'This is ss01 on : 0123456789',
809        search: {
810          fontFeature: "\"ss01\" on"
811        }
812      });
813
814      AtomicServiceSearch({
815        value: 'This is ss01 off : 0123456789',
816        search: {
817          fontFeature: "\"ss01\" off"
818        }
819      });
820
821      AtomicServiceSearch({
822        value: 'fiabc1234567DEFGHIJKLMN',
823        search: {
824          fontFeature: "\"frac\" on"
825        }
826      });
827
828      AtomicServiceSearch({
829        value: 'fiabc1234567DEFGHIJKLMN',
830        search: {
831          fontFeature: "\"frac\" off"
832        }
833      });
834    }.padding({ left: 16, right: 16 })
835  }
836
837  public alert(message: string): void {
838    this.getUIContext().showAlertDialog({ message: message });
839  }
840}
841```
842
843![](figures/AtomicServiceSearchDemo08_frac.png)
844
845
846
847### 示例9(设置文本自适应)
848该示例通过minFontSize、maxFontSize属性展示了文本自适应字号的效果。
849
850```ts
851import { AtomicServiceSearch } from '@kit.ArkUI';
852
853@Entry
854@Component
855struct Index {
856  build() {
857    Column({ space : 10 }) {
858      Text('设置文本自适应').alignSelf(ItemAlign.Start).decoration({
859        type: TextDecorationType.Underline,
860        color: Color.Black,
861        style: TextDecorationStyle.SOLID
862      }).margin({ top: 20, bottom: 20 })
863
864      AtomicServiceSearch({
865        value: 'This is the text without the adaptive font',
866      }).width('80%').height(40).borderWidth(1).borderRadius(20)
867
868      AtomicServiceSearch({
869        value: 'This is the text without the adaptive font',
870        search: {
871          minFontSize: 4,
872          maxFontSize: 40
873        }
874      }).width('80%').height(40).borderWidth(1).borderRadius(20)
875    }.padding({ left: 16, right: 16 })
876  }
877
878  public alert(message: string): void {
879    this.getUIContext().showAlertDialog({ message: message });
880  }
881}
882```
883
884![](figures/AtomicServiceSearchDemo09.png)
885
886
887
888### 示例10(文本扩展自定义菜单)
889该示例通过editMenuOptions接口实现了文本设置自定义菜单扩展项的文本内容、图标以及回调的功能。
890
891```ts
892import { AtomicServiceSearch } from '@kit.ArkUI';
893
894@Entry
895@Component
896struct Index {
897  onCreateMenu = (menuItems: Array<TextMenuItem>) => {
898    let item1: TextMenuItem = {
899      content: 'custom1',
900      icon: $r('app.media.startIcon'),
901      id: TextMenuItemId.of('custom1'),
902    }
903    let item2: TextMenuItem = {
904      content: 'custom2',
905      id: TextMenuItemId.of('custom2'),
906      icon: $r('app.media.startIcon'),
907    }
908    menuItems.push(item1)
909    menuItems.unshift(item2)
910    return menuItems
911  }
912
913  onMenuItemClick = (menuItem: TextMenuItem, textRange: TextRange) => {
914    if (menuItem.id.equals(TextMenuItemId.of("custom2"))) {
915      console.log("拦截 id: custom2 start:" + textRange.start + "; end:" + textRange.end)
916      return true
917    }
918    if (menuItem.id.equals(TextMenuItemId.COPY)) {
919      console.log("拦截 COPY start:" + textRange.start + "; end:" + textRange.end)
920      return true
921    }
922    if (menuItem.id.equals(TextMenuItemId.SELECT_ALL)) {
923      console.log("不拦截 SELECT_ALL start:" + textRange.start + "; end:" + textRange.end)
924      return false
925    }
926    return false
927  }
928
929  @State editMenuOptions: EditMenuOptions = {
930    onCreateMenu: this.onCreateMenu, onMenuItemClick: this.onMenuItemClick
931  }
932
933  build() {
934    Column({ space : 10 }) {
935      Text('文本扩展自定义菜单').alignSelf(ItemAlign.Start).decoration({
936        type: TextDecorationType.Underline,
937        color: Color.Black,
938        style: TextDecorationStyle.SOLID
939      }).margin({ top: 20, bottom: 20 })
940
941      AtomicServiceSearch({
942        value:'Default input',
943        search: {
944          editMenuOptions : this.editMenuOptions
945        }
946      })
947    }.padding({ left: 16, right: 16 })
948  }
949
950  public alert(message: string): void {
951    this.getUIContext().showAlertDialog({ message: message });
952  }
953}
954```
955
956![](figures/AtomicServiceSearchDemo10.gif)
957
958
959
960
961
962### 示例11(设置文本水平对齐/光标样式/选中背景色)
963该示例通过textAlign、caretStyle、selectedBackgroundColor属性展示如何设置文本的水平对齐、光标样式和选中背景色。
964
965```ts
966import { AtomicServiceSearch } from '@kit.ArkUI';
967
968@Entry
969@Component
970struct Index {
971  build() {
972    Column() {
973      Text('设置文本水平对齐/光标样式/选中背景色').alignSelf(ItemAlign.Start).decoration({
974        type: TextDecorationType.Underline,
975        color: Color.Black,
976        style: TextDecorationStyle.SOLID
977      }).margin({ top: 20, bottom: 20 })
978
979      AtomicServiceSearch({
980        value: 'Search textAlign sample',
981        search: {
982          textAlign: TextAlign.Center,
983          caretStyle: { width: 3, color: Color.Green },
984          selectedBackgroundColor: Color.Gray
985        }
986      })
987    }.padding({ left: 16, right: 16 })
988  }
989
990  public alert(message: string): void {
991    this.getUIContext().showAlertDialog({ message: message });
992  }
993}
994```
995
996![](figures/AtomicServiceSearchDemo11.gif)
997
998
999
1000### 示例12(对输入的文本进行过滤)
1001该示例通过inputFilter属性展示如何对输入的文本进行内容的过滤,以限制输入内容。
1002
1003```ts
1004import { AtomicServiceSearch } from '@kit.ArkUI';
1005
1006@Entry
1007@Component
1008struct Index {
1009  @State filterValue: string = '';
1010
1011  build() {
1012    Column() {
1013      Column({ space: 10 }) {
1014        Text('对输入的文本进行过滤').alignSelf(ItemAlign.Start).decoration({
1015          type: TextDecorationType.Underline,
1016          color: Color.Black,
1017          style: TextDecorationStyle.SOLID
1018        }).margin({ top: 20, bottom: 20 })
1019        AtomicServiceSearch({
1020          placeholder: 'please enter...',
1021          search: {
1022            inputFilter: {
1023              inputFilterValue : '[a-z]',
1024              error: (filterValue: string) => {this.filterValue = filterValue}
1025            }
1026          }
1027        })
1028        Text('Filter:' + this.filterValue).alignSelf(ItemAlign.Start)
1029
1030      }
1031    }.padding({ left: 16, right: 16 })
1032  }
1033
1034  public alert(message: string): void {
1035    this.getUIContext().showAlertDialog({ message: message });
1036  }
1037}
1038```
1039
1040![](figures/AtomicServiceSearchDemo12.gif)
1041