HarmonyOS鸿蒙Next中我的第一个应用-随机吃什么

HarmonyOS鸿蒙Next中我的第一个应用-随机吃什么

按照官方开发文档示例先创建一个ArkTS应用。

然后修改index页面

// Index.ets
// 导入页面路由模块
import router from '@ohos.router';
import List from '@ohos.util.List';

@Entry
@Component
struct Index {
// @ts-ignore
@State foodlist: string[] = ['馄饨', '拉面', '烩面', '热干面', '刀削面', '油泼面', '炸酱面', '火锅', '北京烤鸭', '兰州拉面', '四川串串香', '重庆酸辣粉', '武汉热干面', '西安肉夹馍', '长沙小龙虾', '广东肠粉', '小笼包', '广西桂林米粉', '柳州螺蛳粉', '天津煎饼果子']
@State message: string = 'Hello 怪盗LYL'
@State timer: number = 0
@State button_text: string = "随机"
@State check: boolean = false

build() {
  Row() {
    Column() {
      
      Text(this.message)
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
      
      // 添加按钮,以响应用户点击
      Button() {
        Text(this.button_text)
          .fontSize(30)
          .fontWeight(FontWeight.Bold)
      }
      .type(ButtonType.Capsule)
      .margin({
        top: 20
      })
      .backgroundColor('#0D9FFB')
      .width('40%')
      .height('5%')
      // 按钮绑定onClick事件
      .onClick(() => {
        if(!this.check){
        this.button_text = '停止'
        this.check = true
        this.timer = setInterval(() => {
          let randomNumber: number = Math.floor(Math.random() * this.foodlist.length);
          this.message = this.foodlist[randomNumber]
        }, 100); // 每隔100毫秒(1秒)执行一次
        } else {
          // @ts-ignore
          this.button_text = '随机'
          this.check = false
          //清除计时器
          clearInterval(this.timer);
        }
      })

    }
    .width('100%')
  }
  .height('100%')
}

首先是Text和Button两个系统组件,一个是文字一个是按钮。

点击了随机按钮以后,将按钮的文字改成停止,并且校验值改成true,创建一个定时器,定时器每100毫秒执行一次将文字的值变成实物列表随机的下标值。

640.gif


更多关于HarmonyOS鸿蒙Next中我的第一个应用-随机吃什么的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于HarmonyOS鸿蒙Next中我的第一个应用-随机吃什么的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中创建“随机吃什么”应用,首先使用DevEco Studio新建项目,选择“Empty Ability”模板。在MainAbilitySlice中,设计一个包含按钮和文本的简单UI。点击按钮时,调用随机函数从预设的食物列表中选取一项,并显示在文本框中。核心代码包括随机数生成和UI更新逻辑。完成后,通过模拟器或真机测试应用,确保功能正常。此应用展示了HarmonyOS的基本开发流程和UI交互实现。

回到顶部