DEV Community

HarmonyOS
HarmonyOS

Posted on

How can I make the Badge component work when clicking the grayed-out area and when using a button?

Read the original article:How can I make the Badge component work when clicking the grayed-out area and when using a button?

Problem Description

Currently, only the blue part of the button responds to the click event; the part covered by the gray dot does not respond to clicks. How can I implement it so that clicking both the gray dot area and the button trigger the click event?

The code for the problem is as follows:

@Entry
@Component
struct BadgeClickTest {
  @State badgeCount: number = 80;

  build() {
    Stack() {
      Badge({
        count: this.badgeCount,
        maxCount: 99,
        position: { x: 90, y: 5 },
        style: {
          fontSize: '20vp',
          badgeColor: '#ff919191',
          badgeSize: 30,
          borderWidth: 0
        }
      }) {
        Button('Click+1')
          .width(170)
          .padding({ left: 25 })
          .fontSize(18)
          .align(Alignment.Start)
          .onClick(() => {
            this.badgeCount += 1
          })
          .backgroundColor('#0D5AF5')
      }
    }.width('100%').height('100%')
  }
}
Enter fullscreen mode Exit fullscreen mode

Background Knowledge

  • Badge: An information marking component, which is a container component that can be attached to a single component for information reminders.
  • Stack: A stacking container where child components are pushed onto the stack sequentially, and the later child component covers the previous one.

Solution

By migrating the button's click event to the Badge component, you can ensure that clicking both the gray dot area and the button trigger the event.

Sample code is provided below:

@Entry
@Component
struct BadgeClickTest {
  @State badgeCount: number = 80;

  build() {
    Stack() {
      Badge({
        count: this.badgeCount,
        maxCount: 99,
        position: { x: 90, y: 5 },
        style: {
          fontSize: '20vp',
          badgeColor: '#ff919191',
          badgeSize: 30,
          borderWidth: 0
        }
      }) {
        Button('Click +1')
          .width(170)
          .padding({ left: 25 })
          .fontSize(18)
          .align(Alignment.Start).backgroundColor(Color.Green)
      }
      .onClick(() => {
        // Migrate button click events to the Badge component
        this.badgeCount += 1;
      })
    }
    .width('100%')
    .height('100%')
  }
}
Enter fullscreen mode Exit fullscreen mode

cke_1105.gif

Verification Result

This example supports API Version 20 Release and later versions.

This example supports HarmonyOS 6.0.0 Release SDK and later versions.

This example requires DevEco Studio 6.0.0 Release or later for building and running.

Written by Muhammet Ali Ilgaz

Top comments (0)