HarmonyOS Next 教育应用之考试页面开发(二)

144 阅读2分钟

3. 倒计时功能实现

使用 TextTimer 组件实现倒计时功能,设置倒计时时间和格式,监听倒计时事件,当倒计时结束时强制提交试卷。同时,在页面切换时保存当前倒计时时间。

TextTimer({ isCountDown: true, count: this.count, controller: this.textTimerController })
  .format(this.format)
  .fontColor(Color.Black)
  .fontSize(30)
  .onTimer((utc: number, elapsedTime: number) => {
    this.elapsedTime = this.count - elapsedTime * 1000;
    if (elapsedTime * 1000 === this.count) {
      //倒计时结束
      this.submit(true);
    }
  })
  .onAppear(() => {
    this.textTimerController.start();
  })
  .onDisAppear(() => {
    //页面切换,保存当前的值
    AppStorage.setOrCreate('MyCount', this.elapsedTime);
  })

该功能保证了考试时间的准确控制,并且在页面切换时不会丢失倒计时进度。

4. 试题展示与切换

通过 ForEach 组件遍历当前试题的选项并展示,使用按钮实现上一题和下一题的切换功能。

Text(this.currentModel!.title)
  .fontWeight(FontWeight.Medium)
  .fontColor('333333').margin({ top: 10, left: 10, right: 10 })

Column() {
  ForEach(this.currentModel!.ques, ((item: string) => {
    Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center }) {
      Text(item)
        .fontColor('#3333333').margin({ left: 5 })
    }.backgroundColor('#eeeeeee').height(50)
    .margin({ top: 8 })
    .borderRadius(5)
  }))
}.margin({ left: 10, right: 10 })

Button('上一题', { buttonStyle: ButtonStyleMode.NORMAL })
  .width(80)
  .height(30)
  .borderStyle(BorderStyle.Solid)
  .borderWidth(1)
  .borderColor(Color.Blue)
  .borderRadius(10)
  .backgroundColor(Color.White)
  .fontColor(Color.Blue)
  .onClick(() => {
    if (this.currentIndex > 0) {
      this.currentIndex -= 1
      this.currentModel = errorModels[this.currentIndex]
    }
  })
  .margin({ left: 10 })

Button(this.nextBtnText, { buttonStyle: ButtonStyleMode.NORMAL })
  .backgroundColor(Color.White)
  .width(80)
  .height(30)
  .borderStyle(BorderStyle.Solid)
  .borderWidth(1)
  .borderColor(Color.Blue)
  .borderRadius(10)
  .fontColor(Color.Blue)
  .onClick(() => {
    this.submit(false);
  })
  .margin({ right: 10 })

这些代码实现了试题的展示和答题过程中的切换功能,方便用户进行答题操作。

5. 试卷提交功能

submit 方法处理试卷提交逻辑,根据是否强制提交和是否到达最后一题进行不同处理,最后一题时弹出确认对话框。

submit(force: Boolean): void {
  if (force) {
    //考试时间到,强制提交
    this.pathStack.pushPathByName('MineTestResPage', null);
    AppStorage.setOrCreate('MyCount', 0);
  } else {
    this.currentIndex += 1
    if ((this.currentIndex + 1) < errorModels.length) {
      this.currentModel = errorModels[this.currentIndex]
    } else {
      //弹窗展示
      this.nextBtnText = '交卷'
      this.tjDialog.open()
    }
  }
}

该方法确保了试卷提交的逻辑完整性,既支持时间到的强制提交,也支持用户主动交卷。

总结

通过上述代码,利用 HarmonyOS Next 的 ArkTS 开发框架,成功实现了一个教育应用的考试页面。该页面具备倒计时、试题展示、答题切换和提交试卷等功能,体现了 HarmonyOS Next 开发的高效性和灵活性。开发者可以根据实际需求进一步扩展页面功能,如增加答题交互逻辑、完善提交试卷后的结果展示等。