• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Rating
2
3The **Rating** component provides a rating bar.
4
5>  **NOTE**
6>
7>  This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
8
9
10## Child Components
11
12Not supported
13
14
15## APIs
16
17Rating(options?: RatingOptions)
18
19**Widget capability**: This API can be used in ArkTS widgets since API version 9.
20
21**Atomic service API**: This API can be used in atomic services since API version 11.
22
23**System capability**: SystemCapability.ArkUI.ArkUI.Full
24
25**Parameters**
26
27| Name | Type                                     | Mandatory| Description          |
28| ------- | ----------------------------------------- | ---- | -------------- |
29| options | [RatingOptions](#ratingoptions18) | No  | Rating bar options.|
30
31## Attributes
32
33### stars
34
35stars(value: number)
36
37Sets the total number of ratings (stars). If the value set is less than or equal to 0, the default value is used.
38
39**Widget capability**: This API can be used in ArkTS widgets since API version 9.
40
41**Atomic service API**: This API can be used in atomic services since API version 11.
42
43**System capability**: SystemCapability.ArkUI.ArkUI.Full
44
45**Parameters**
46
47| Name| Type  | Mandatory| Description                        |
48| ------ | ------ | ---- | ---------------------------- |
49| value  | number | Yes  | Total number of ratings.<br>Default value: **5**|
50
51### stars<sup>18+</sup>
52
53stars(starCount: Optional\<number>)
54
55Sets the total number of ratings (stars). If the value set is less than or equal to 0, the default value is used. Compared to [stars](#stars), this API supports the **undefined** type for the **starCount** parameter.
56
57**Widget capability**: This API can be used in ArkTS widgets since API version 18.
58
59**Atomic service API**: This API can be used in atomic services since API version 18.
60
61**System capability**: SystemCapability.ArkUI.ArkUI.Full
62
63**Parameters**
64
65| Name   | Type                                                        | Mandatory| Description                                                      |
66| --------- | ------------------------------------------------------------ | ---- | ---------------------------------------------------------- |
67| starCount | [Optional](ts-universal-attributes-custom-property.md#optional12)\<number> | Yes  | Total number of ratings.<br>If **starCount** is set to **undefined**, the default value **5** is used.|
68
69### stepSize
70
71stepSize(value: number)
72
73Sets the step for rating. A value less than 0.1 evaluates to the default value.
74
75**Widget capability**: This API can be used in ArkTS widgets since API version 9.
76
77**Atomic service API**: This API can be used in atomic services since API version 11.
78
79**System capability**: SystemCapability.ArkUI.ArkUI.Full
80
81**Parameters**
82
83| Name| Type  | Mandatory| Description                                                       |
84| ------ | ------ | ---- | ----------------------------------------------------------- |
85| value  | number | Yes  | Step for rating.<br>Default value: **0.5**<br>Value range: [0.1, stars]|
86
87### stepSize<sup>18+</sup>
88
89stepSize(size: Optional\<number>)
90
91Sets the step for rating. A value less than 0.1 evaluates to the default value. Compared to [stepSize](#stepsize), this API supports the **undefined** type for the **size** parameter.
92
93**Widget capability**: This API can be used in ArkTS widgets since API version 18.
94
95**Atomic service API**: This API can be used in atomic services since API version 18.
96
97**System capability**: SystemCapability.ArkUI.ArkUI.Full
98
99**Parameters**
100
101| Name| Type                                                        | Mandatory| Description                                                        |
102| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
103| size   | [Optional](ts-universal-attributes-custom-property.md#optional12)\<number> | Yes  | Step for rating.<br>If **size** is set to **undefined**, the default value **0.5** is used.<br>Value range: [0.1, stars]|
104
105### starStyle
106
107starStyle(options: StarStyleOptions)
108
109Sets the star style. For details about the supported image types, see [Image](ts-basic-components-image.md).
110
111Local and online images are supported, but not **PixelMap** and **Resource** objects.
112
113By default, the image is loaded in asynchronous mode. Synchronous loading is not supported.
114
115**Widget capability**: This API can be used in ArkTS widgets since API version 9.
116
117**Atomic service API**: This API can be used in atomic services since API version 11.
118
119**System capability**: SystemCapability.ArkUI.ArkUI.Full
120
121**Parameters**
122
123| Name | Type                                           | Mandatory| Description                                                        |
124| ------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ |
125| options | [StarStyleOptions](#starstyleoptions18) | Yes  | Star style.<br>**NOTE**<br>If the path specified for **backgroundUri**, **foregroundUri**, or **secondaryUri** is incorrect, no image is displayed.<br>If **backgroundUri** or **foregroundUri** is set to **undefined** or an empty string, the **Rating** component loads the default star image source.<br>If **secondaryUri** is set to **undefined** or an empty string or is not set, **backgroundUri** is prioritized, which is equivalent to where only **foregroundUri** and **backgroundUri** are set.|
126
127### starStyle<sup>18+</sup>
128
129starStyle(options: Optional\<StarStyleOptions>)
130
131Sets the star style. For details about the supported image types, see [Image](ts-basic-components-image.md).
132
133Local and online images are supported, but not **PixelMap** and **Resource** objects.
134
135By default, the image is loaded in asynchronous mode. Synchronous loading is not supported.
136
137Compared to [starStyle](#starstyle), this API supports the **undefined** type for the **options** parameter.
138
139**Widget capability**: This API can be used in ArkTS widgets since API version 18.
140
141**Atomic service API**: This API can be used in atomic services since API version 18.
142
143**System capability**: SystemCapability.ArkUI.ArkUI.Full
144
145**Parameters**
146
147| Name | Type                                                        | Mandatory| Description                                                        |
148| ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
149| options | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[StarStyleOptions](#starstyleoptions18)> | Yes  | Star style.<br>**NOTE**<br>If the path specified for **backgroundUri**, **foregroundUri**, or **secondaryUri** is incorrect, no image is displayed.<br>If **backgroundUri** or **foregroundUri** is set to **undefined** or an empty string, the **Rating** component loads the default star image source.<br>If **secondaryUri** is set to **undefined** or an empty string or is not set, **backgroundUri** is prioritized, which is equivalent to where only **foregroundUri** and **backgroundUri** are set.|
150
151>  **NOTE**
152>
153>  The drawing area of each rating image is [width/stars, height], wherein **width** and **height** indicate the width and height of the **Rating** component, respectively.
154>
155>  To specify the drawing area as a square, you are advised to customize the width and height in this format: [height * stars, height], width = height * stars.
156
157### contentModifier<sup>12+</sup>
158
159contentModifier(modifier: ContentModifier\<RatingConfiguration>)
160
161Creates a content modifier.
162
163**Atomic service API**: This API can be used in atomic services since API version 12.
164
165**System capability**: SystemCapability.ArkUI.ArkUI.Full
166
167**Parameters**
168
169| Name| Type                                         | Mandatory| Description                                            |
170| ------ | --------------------------------------------- | ---- | ------------------------------------------------ |
171| modifier  | [ContentModifier\<RatingConfiguration>](#ratingconfiguration12) | Yes  | Content modifier to apply to the current component.<br>**modifier**: content modifier. You need a custom class to implement the **ContentModifier** API.|
172
173### contentModifier<sup>18+</sup>
174
175contentModifier(modifier: Optional<ContentModifier\<RatingConfiguration>>)
176
177Creates a content modifier. Compared to [contentModifier](#contentmodifier12), this API supports the **undefined** type for the **modifier** parameter.
178
179**Atomic service API**: This API can be used in atomic services since API version 18.
180
181**System capability**: SystemCapability.ArkUI.ArkUI.Full
182
183**Parameters**
184
185| Name  | Type                                                        | Mandatory| Description                                                        |
186| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
187| modifier | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[ContentModifier\<RatingConfiguration>](#ratingconfiguration12)> | Yes  | Content modifier to apply to the current component.<br>**modifier**: content modifier. You need a custom class to implement the **ContentModifier** API.<br>If **modifier** is set to **undefined**, no content modifier is used.|
188
189## Events
190
191### onChange
192
193onChange(callback:(value: number) =&gt; void)
194
195Triggered when the rating value changes.
196
197**Widget capability**: This API can be used in ArkTS widgets since API version 9.
198
199**Atomic service API**: This API can be used in atomic services since API version 11.
200
201**System capability**: SystemCapability.ArkUI.ArkUI.Full
202
203**Parameters**
204
205| Name| Type  | Mandatory| Description          |
206| ------ | ------ | ---- | -------------- |
207| value  | number | Yes  | Rating value.|
208
209### onChange<sup>18+</sup>
210
211onChange(callback:Optional\<OnRatingChangeCallback>)
212
213Triggered when the rating value changes. Compared to [onChange](#onchange), this API supports the **undefined** type for the **callback** parameter.
214
215**Widget capability**: This API can be used in ArkTS widgets since API version 18.
216
217**Atomic service API**: This API can be used in atomic services since API version 18.
218
219**System capability**: SystemCapability.ArkUI.ArkUI.Full
220
221**Parameters**
222
223| Name  | Type                                                        | Mandatory| Description                                                        |
224| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
225| callback | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[OnRatingChangeCallback](#onratingchangecallback18)> | Yes  | Triggered when the rating value changes.<br>If **callback** is set to **undefined**, the callback function is not used.|
226
227## OnRatingChangeCallback<sup>18+</sup>
228
229type OnRatingChangeCallback = (rating: number) => void
230
231Triggered when the rating value changes.
232
233**Atomic service API**: This API can be used in atomic services since API version 18.
234
235**System capability**: SystemCapability.ArkUI.ArkUI.Full
236
237**Parameters**
238
239| Name| Type  | Mandatory| Description          |
240| ------ | ------ | ---- | -------------- |
241| rating | number | Yes  | Rating value.|
242
243## Sequential Keyboard Navigation Specifications
244| Key        | Description                       |
245|------------|-----------------------------|
246| Tab        | Switch the focus between components.                   |
247| Left and right arrow keys  | Increase or decrease the rating on preview at the specified step, without changing the actual rating.|
248| Home       | Move the focus to the first star, without changing the actual rating.         |
249| End        | Move the focus to the last star, without changing the actual rating.        |
250| Space/Enter | Submit the rating result based on the current rating.              |
251
252## RatingConfiguration<sup>12+</sup>
253
254You need a custom class to implement the **ContentModifier** API.
255
256**Atomic service API**: This API can be used in atomic services since API version 12.
257
258**System capability**: SystemCapability.ArkUI.ArkUI.Full
259
260| Name | Type   |    Read Only   |    Optional     |  Description             |
261| ------ | ------ | ------ |-------------------------------- |-------------------------------- |
262| rating    | number  | No| No| Value to rate.<br>Default value: **0**<br>Value range: [0, stars]<br>Values less than 0 are treated as **0**, and values greater than the value of [stars](#stars) are treated as the value of **stars**.<br>This parameter supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md).<br>This parameter supports two-way binding through [!!](../../../quick-start/arkts-new-binding.md).|
263| indicator | boolean | No| No| Whether the rating bar is used as an indicator.<br>**true**: The rating bar is used as an indicator.<br>**false**: The rating bar is not used as an indicator.<br>Default value: **false**|
264| stars | number | No| No|Total number of ratings.<br>Default value: **5**|
265| stepSize | number | No| No|Step of an operation.<br>Default value: **0.5**|
266| triggerChange | Callback\<number> | No| No|Callback triggered when the rating value changes.|
267
268## RatingOptions<sup>18+</sup>
269
270**Widget capability**: This API can be used in ArkTS widgets since API version 18.
271
272**Atomic service API**: This API can be used in atomic services since API version 18.
273
274**System capability**: SystemCapability.ArkUI.ArkUI.Full
275
276| Name                  | Type   | Mandatory| Description                                                        |
277| ---------------------- | ------- | ---- | ------------------------------------------------------------ |
278| rating<sup>7+</sup>    | number  | Yes  | Value to rate.<br>Default value: **0**<br>Value range: [0, stars]<br>Values less than 0 are treated as **0**, and values greater than the value of [stars](#stars) are treated as the value of **stars**.<br>This parameter supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md).<br>**Widget capability**: This API can be used in ArkTS widgets since API version 9.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
279| indicator<sup>7+</sup> | boolean | No  | Whether the component is used only as an indicator.<br>Default value: **false**<br>**NOTE**<br>When **indicator** is set to **true**, the default component height is 12.0 vp, and the component width is calculated as follows: Height x Value of **stars**.<br>When **indicator** is set to **false**, the default component height is 28.0 vp, and the component width is calculated as follows: Height x Value of **stars**.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 9.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
280
281## StarStyleOptions<sup>18+</sup>
282
283**Widget capability**: This API can be used in ArkTS widgets since API version 18.
284
285**Atomic service API**: This API can be used in atomic services since API version 18.
286
287**System capability**: SystemCapability.ArkUI.ArkUI.Full
288
289| Name                      | Type  | Mandatory| Description                                                        |
290| -------------------------- | ------ | ---- | ------------------------------------------------------------ |
291| backgroundUri<sup>7+</sup> | string | Yes  | Image path for the unselected star. You can use the default system image or a custom image.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 9.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
292| foregroundUri<sup>7+</sup> | string | Yes  | Image path for the selected star. You can use the default system image or a custom image.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 9.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
293| secondaryUri<sup>7+</sup>  | string | No  | Image path for the partially selected star. You can use the default system image or a custom image.<br>**Widget capability**: This API can be used in ArkTS widgets since API version 9.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
294
295## Example
296
297### Example 1: Setting the Default Rating Style
298
299This example demonstrates how to set the default star rating style.
300
301```ts
302// xxx.ets
303@Entry
304@Component
305struct RatingExample {
306  @State rating: number = 3.5
307
308  build() {
309    Column() {
310      Column() {
311        Rating({ rating: this.rating, indicator: false })
312          .stars(5)
313          .stepSize(0.5)
314          .margin({ top: 24 })
315          .onChange((value: number) => {
316            this.rating = value
317          })
318        Text('current score is ' + this.rating)
319          .fontSize(16)
320          .fontColor('rgba(24,36,49,0.60)')
321          .margin({ top: 16 })
322      }.width(360).height(113).backgroundColor('#FFFFFF').margin({ top: 68 })
323
324      Row() {
325        Image('common/testImage.jpg')
326          .width(40)
327          .height(40)
328          .borderRadius(20)
329          .margin({ left: 24 })
330        Column() {
331          Text('Yue')
332            .fontSize(16)
333            .fontColor('#182431')
334            .fontWeight(500)
335          Row() {
336            Rating({ rating: 3.5, indicator: false }).margin({ top: 1, right: 8 })
337            Text('2021/06/02')
338              .fontSize(10)
339              .fontColor('#182431')
340          }
341        }.margin({ left: 12 }).alignItems(HorizontalAlign.Start)
342
343        Text('1st Floor')
344          .fontSize(10)
345          .fontColor('#182431')
346          .position({ x: 295, y: 8 })
347      }.width(360).height(56).backgroundColor('#FFFFFF').margin({ top: 64 })
348    }.width('100%').height('100%').backgroundColor('#F1F3F5')
349  }
350}
351```
352
353![rating](figures/rating.gif)
354
355### Example 2: Customizing the Rating Style
356
357This example demonstrates how to configure **starStyle** to use custom image links for stars.
358
359```ts
360// xxx.ets
361@Entry
362@Component
363struct RatingExample {
364  @State rating: number = 3.5
365
366  build() {
367    Column() {
368      Rating({ rating: this.rating, indicator: false })
369        .stars(5)
370        .stepSize(0.5)
371        .starStyle({
372          backgroundUri: '/common/imag1.png', // The common folder is at the same level as pages.
373          foregroundUri: '/common/imag2.png',
374          secondaryUri: '/common/imag3.png'
375        })
376        .margin({ top: 24 })
377        .onChange((value: number) => {
378          this.rating = value
379        })
380      Text('current score is ' + this.rating)
381        .fontSize(16)
382        .fontColor('rgba(24,36,49,0.60)')
383        .margin({ top: 16 })
384    }.width('100%').height('100%').backgroundColor('#F1F3F5')
385  }
386}
387```
388
389![rating1](figures/rating1.gif)
390
391### Example 3: Implementing a Custom Rating Bar
392This example implements a custom rating bar, with each circle representing 0.5 point. If **ratingIndicator** is set to **true**, the rating bar is used only as an indicator, and the rating cannot be changed.
393if it is set to **false**, the rating can be changed. **ratingStars** sets the rating value. **ratingStepsize** sets the step for rating.
394
395```ts
396// xxx.ets
397class MyRatingStyle implements ContentModifier<RatingConfiguration> {
398  name: string = ""
399  style: number = 0
400  constructor(value1: string, value2: number) {
401    this.name = value1
402    this.style = value2
403  }
404  applyContent() : WrappedBuilder<[RatingConfiguration]> {
405    return wrapBuilder(buildRating)
406  }
407}
408
409@Builder function buildRating(config: RatingConfiguration) {
410  Column() {
411    Row() {
412      Circle({ width: 25, height: 25 })
413        .fill(config.rating >= 0.4 ? Color.Black : Color.Red)
414        .onClick((event: ClickEvent) => {
415          if (!config.indicator) {
416            if (config.stepSize = 0.5) {
417              config.triggerChange(0.5);
418              return
419            }
420            if (config.stepSize = 1) {
421              config.triggerChange(1);
422              return
423            }
424          }
425        }).visibility(config.stars >= 1 ? Visibility.Visible : Visibility.Hidden)
426      Circle({ width: 25, height: 25 })
427        .fill(config.rating >= 0.9 ? Color.Black : Color.Red)
428        .onClick((event: ClickEvent) => {
429          if (!config.indicator) {
430            config.triggerChange(1);
431          }
432        }).visibility(config.stars >= 1 ? Visibility.Visible : Visibility.Hidden)
433      Circle({ width: 25, height: 25 })
434        .fill(config.rating >= 1.4 ? Color.Black : Color.Red)
435        .onClick((event: ClickEvent) => {
436          if (!config.indicator) {
437            if (config.stepSize = 0.5) {
438              config.triggerChange(1.5);
439              return
440            }
441            if (config.stepSize = 1) {
442              config.triggerChange(2);
443              return
444            }
445          }
446        }).visibility(config.stars >= 2 ? Visibility.Visible : Visibility.Hidden).margin({left:10})
447      Circle({ width: 25, height: 25 })
448        .fill(config.rating >= 1.9 ? Color.Black : Color.Red)
449        .onClick((event: ClickEvent) => {
450          if (!config.indicator) {
451            config.triggerChange(2);
452          }
453        }).visibility(config.stars >= 2 ? Visibility.Visible : Visibility.Hidden)
454      Circle({ width: 25, height: 25 })
455        .fill(config.rating >= 2.4 ? Color.Black : Color.Red)
456        .onClick((event: ClickEvent) => {
457          if (!config.indicator) {
458            if (config.stepSize = 0.5) {
459              config.triggerChange(2.5);
460              return
461            }
462            if (config.stepSize = 1) {
463              config.triggerChange(3);
464              return
465            }
466          }
467        }).visibility(config.stars >= 3 ? Visibility.Visible : Visibility.Hidden).margin({left:10})
468      Circle({ width: 25, height: 25 })
469        .fill(config.rating >= 2.9 ? Color.Black : Color.Red)
470        .onClick((event: ClickEvent) => {
471          if (!config.indicator) {
472            config.triggerChange(3);
473          }
474        }).visibility(config.stars >= 3 ? Visibility.Visible : Visibility.Hidden)
475      Circle({ width: 25, height: 25 })
476        .fill(config.rating >= 3.4 ? Color.Black : Color.Red)
477        .onClick((event: ClickEvent) => {
478          if (!config.indicator) {
479            if (config.stepSize = 0.5) {
480              config.triggerChange(3.5);
481              return
482            }
483            if (config.stepSize = 1) {
484              config.triggerChange(4);
485              return
486            }
487          }
488        }).visibility(config.stars >= 4 ? Visibility.Visible : Visibility.Hidden).margin({left:10})
489      Circle({ width: 25, height: 25 })
490        .fill(config.rating >= 3.9 ? Color.Black : Color.Red)
491        .onClick((event: ClickEvent) => {
492          if (!config.indicator) {
493            config.triggerChange(4);
494          }
495        }).visibility(config.stars >= 4 ? Visibility.Visible : Visibility.Hidden)
496      Circle({ width: 25, height: 25 })
497        .fill(config.rating >= 4.4 ? Color.Black : Color.Red)
498        .onClick((event: ClickEvent) => {
499          if (!config.indicator) {
500            if (config.stepSize = 0.5) {
501              config.triggerChange(4.5);
502              return
503            }
504            if (config.stepSize = 1) {
505              config.triggerChange(5);
506              return
507            }
508          }
509        }).visibility(config.stars >= 5 ? Visibility.Visible : Visibility.Hidden).margin({left:10})
510      Circle({ width: 25, height: 25 })
511        .fill(config.rating >= 4.9 ? Color.Black : Color.Red)
512        .onClick((event: ClickEvent) => {
513          if (!config.indicator) {
514            config.triggerChange(5);
515          }
516        }).visibility(config.stars >= 5 ? Visibility.Visible : Visibility.Hidden)
517    }
518    Text("Rating: "+ config.rating)
519  }
520}
521
522@Entry
523@Component
524struct ratingExample {
525  @State rating: number = 0;
526  @State ratingIndicator: boolean = true;
527  @State ratingStars: number = 0;
528  @State ratingStepsize: number = 0.5;
529  @State ratingEnabled: boolean = true;
530  build() {
531    Row() {
532      Column() {
533        Rating({
534          rating: 0,
535          indicator: this.ratingIndicator
536        })
537          .stepSize(this.ratingStepsize)
538          .stars(this.ratingStars)
539          .backgroundColor(Color.Transparent)
540          .width('100%')
541          .height(50)
542          .onChange((value: number) => {
543            console.info('Rating change is'+ value);
544            this.rating = value
545          })
546          .contentModifier(new MyRatingStyle("hello", 3))
547        Button(this.ratingIndicator ? "ratingIndicator : true" : "ratingIndicator : false")
548          .onClick((event) => {
549            if (this.ratingIndicator) {
550              this.ratingIndicator = false
551            } else {
552              this.ratingIndicator = true
553            }
554          }).margin({top : 5})
555
556        Button(this.ratingStars < 5 ? "ratingStars + 1, ratingStars = " + this.ratingStars : "Maximum value of ratingStars: 5")
557          .onClick((event) => {
558            if (this.ratingStars < 5) {
559              this.ratingStars += 1
560            }
561          }).margin({top : 5})
562
563        Button(this.ratingStars > 0 ? "ratingStars - 1, ratingStars = " + this.ratingStars : "Values less than or equal to 0 are handled as 5")
564          .onClick((event) => {
565            if (this.ratingStars > 0) {
566              this.ratingStars -= 1
567            }
568          }).margin({top : 5})
569
570        Button(this.ratingStepsize == 0.5 ? "ratingStepsize : 0.5" : "ratingStepsize : 1")
571          .onClick((event) => {
572            if (this.ratingStepsize == 0.5) {
573              this.ratingStepsize = 1
574            } else {
575              this.ratingStepsize = 0.5
576            }
577          }).margin({top : 5})
578      }
579      .width('100%')
580      .height('100%')
581      .justifyContent(FlexAlign.Center)
582    }
583    .height('100%')
584  }
585}
586```
587
588![rating2](figures/rating2.gif)
589