HarmonyOS 自定义Slider?

有如图所示的Slider组件实现方案吗,可以自定义文本显示进度?

阅读 498
1 个回答

请参考以下代码调整样式和增加其他逻辑:

文档支持:https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-slider.md\#trackthickness8

const BLOCK_DEFAULT_BORDER_WIDTH = 4;

@Entry
@Component
struct SliderIndex {
  @State progress: number = 0
  @State isTipShow: boolean = false;
  @State tipsOffset: number = 0;
  private slideHeight: number = 300;
  private blockSize: number = 20;
  private tipHeight: number = 40;
  private hideTipTask?: number;

  aboutToAppear(): void {
    //定时器模拟播放进度
    setInterval(() => {
      this.progress++
    }, 1000)
  }

  private showTip(value: number) {
    this.isTipShow = true
    let percent = Number((value / 100).toFixed(2));
    this.tipsOffset = (this.slideHeight - this.blockSize - BLOCK_DEFAULT_BORDER_WIDTH * 2) * percent - (this.tipHeight / 2 - (this.blockSize / 2 + BLOCK_DEFAULT_BORDER_WIDTH));
  }

  private hideTip() {
    clearTimeout(this.hideTipTask)
    this.hideTipTask = setTimeout(() => {
      this.isTipShow = false
    }, 3000)
  }

  build() {
    Row() {
      Slider({ direction: Axis.Vertical, value: this.progress})
        .height(this.slideHeight)
        .selectedColor(Color.Green)
        .trackColor('#5a5a5a')
        .trackThickness(10)
        .blockSize({ width: this.blockSize, height: this.blockSize })
        .selectedColor('#FF6103')
        .onChange((value: number, mode: SliderChangeMode) => {
          this.progress = value
          switch (mode) {
            case SliderChangeMode.Moving:
            case SliderChangeMode.Click:
              this.showTip(value);
              break;
            case SliderChangeMode.End:
              this.hideTip();
              break;
          }
        })
      if (this.isTipShow) {
        Text("01:55/02:22")
          .fontSize(12)
          .height(this.tipHeight)
          .offset({ y: this.tipsOffset })
          .fontColor(Color.White)
          .backgroundColor("#66000000")
          .padding(10)
          .borderRadius(5)
          .hitTestBehavior(HitTestMode.Transparent)
      }
    }
    .alignItems(VerticalAlign.Top)
    .padding(20)
    .height('100%')
    .width('100%')
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进