HarmonyOS Button stateEffect自定义咨询

开启Button stateEffect为true后,如何自定义按压后的背景颜色或者按压后的背景图标?

HarmonyOS
2025-01-09 16:28:18
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
aquaa

可以使用在Button组件上定制Button内容区的方法,自定义class来实现ContentModifier接口。参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-basic-components-button-V5#contentmodifier12

class MyButtonStyle implements ContentModifier<ButtonConfiguration> {
  x: number = 0
  y: number = 0
  selectedColor: Color = Color.Black

  constructor(x: number, y: number, ColorType: Color) {
    this.x = x
    this.y = y
    this.selectedColor = ColorType
  }

  applyContent(): WrappedBuilder<[ButtonConfiguration]> {
    return wrapBuilder(buildButton1)
  }
}

@Builder
function buildButton1(config: ButtonConfiguration) {
  Column({ space: 30 }) {
    Text(config.enabled ? "enabled true" : "enabled false")
    Text('圆圈状态' + (config.pressed ? "( 按压 )" : "( 非按压 )"))
    Text('点击位置x坐标:' + (config.enabled ? (config.contentModifier as MyButtonStyle).x : "0"))
    Text('点击位置y坐标:' + (config.enabled ? (config.contentModifier as MyButtonStyle).y : "0"))
    Circle({ width: 50, height: 50 })
      .fill(config.pressed ? (config.contentModifier as MyButtonStyle).selectedColor : Color.Black)
      .gesture(
        TapGesture({ count: 1 }).onAction((event: GestureEvent) => {
          config.triggerClick(event.fingerList[0].localX, event.fingerList[0].localY)
        })).opacity(config.enabled ? 1 : 0.1)
  }
}

@Entry
@Component
struct ButtonExample {
  @State buttonEnabled: boolean = true;
  @State positionX: number = 0
  @State positionY: number = 0
  @State state: boolean[] = [true, false]
  @State index: number = 0

  build() {
    Column() {
      Button('OK')
        .contentModifier(new MyButtonStyle(this.positionX, this.positionY, Color.Red))
        .onClick((event) => {
          console.info('change' + JSON.stringify(event))
          this.positionX = event.displayX
          this.positionY = event.displayY
        }).enabled(this.buttonEnabled)
      Row() {
        Toggle({ type: ToggleType.Switch, isOn: true }).onChange((value: boolean) => {
          if (value) {
            this.buttonEnabled = true
          } else {
            this.buttonEnabled = false
          }
        }).margin({ left: -80 })
      }
    }.height('100%').width('100%').justifyContent(FlexAlign.Center)
  }
}
分享
微博
QQ
微信
回复
2025-01-09 19:27:13
相关问题
HarmonyOS 自定义扫码咨询
352浏览 • 1回复 待解决
HarmonyOS 自定义相册方案咨询
364浏览 • 1回复 待解决
HarmonyOS自定义相册选择页面咨询
769浏览 • 1回复 待解决
HarmonyOS 工具类自定义弹窗方案咨询
446浏览 • 1回复 待解决
多module场景Hvigor自定义扩展咨询
1053浏览 • 1回复 待解决
自定义弹窗自定义转场动画
1498浏览 • 1回复 待解决
HarmonyOS 定义自定义组件
506浏览 • 1回复 待解决
HarmonyOS 自定义键盘
657浏览 • 1回复 待解决
HarmonyOS 自定义Slider
433浏览 • 1回复 待解决
HarmonyOS 自定义UA
417浏览 • 1回复 待解决
HarmonyOS 地图自定义marker
416浏览 • 1回复 待解决
HarmonyOS 自定义全屏dialog
448浏览 • 1回复 待解决