> 文档中心 > 【鸿蒙】 使用定时器做一个简单的抢红包小游戏

【鸿蒙】 使用定时器做一个简单的抢红包小游戏


1.新建项目

【鸿蒙】 使用定时器做一个简单的抢红包小游戏

【鸿蒙】 使用定时器做一个简单的抢红包小游戏

【鸿蒙】 使用定时器做一个简单的抢红包小游戏

2. 添加 计时器,按钮组件

【鸿蒙】 使用定时器做一个简单的抢红包小游戏

        

3.抢红包业务逻辑

【鸿蒙】 使用定时器做一个简单的抢红包小游戏

package com.sgg.hongbao.slice;import com.sgg.hongbao.ResourceTable;import ohos.aafwk.ability.AbilitySlice;import ohos.aafwk.content.Intent;import ohos.agp.components.Button;import ohos.agp.components.TickTimer;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.logging.SimpleFormatter;public class MainAbilitySlice extends AbilitySlice {    Long money = 0L;    @Override    public void onStart(Intent intent) { super.onStart(intent); super.setUIContent(ResourceTable.Layout_ability_main); // 获取定时器组件 TickTimer tickTimer = (TickTimer) findComponentById(ResourceTable.Id_tick_1); //获取按钮组件 Button bt = (Button) findComponentById(ResourceTable.Id_bt_1); tickTimer.setCountDown(false); tickTimer.start(); // 10S 准备时间 int countDwonTime = 3; tickTimer.setTickListener(tickTimer1 -> {     Long aLong = string2Long(tickTimer1.getText());     Long time = countDwonTime - aLong;     if (aLong >= 10) {  bt.setText(" 恭喜你 抢到 " + money + " 元 ");  bt.setMultipleLine(true);  //关闭定时器  tickTimer.setText(" 00 : 00 ");  tickTimer.stop();  return;     }     if (time  {     money+=1000; });    }    private Long string2Long(String str) { long time = 0; try {     time = new SimpleDateFormat("mm:ss").parse(str).getSeconds(); } catch (ParseException e) {     e.printStackTrace(); } return time;    }    @Override    public void onActive() { super.onActive();    }    @Override    public void onForeground(Intent intent) { super.onForeground(intent);    }}

4.效果演示

【鸿蒙】 使用定时器做一个简单的抢红包小游戏

开发者涨薪指南 【鸿蒙】 使用定时器做一个简单的抢红包小游戏 48位大咖的思考法则、工作方式、逻辑体系